问题
I have this class that needs to be serialized to json:
[DataContract]
public class InfoRequest
{
[DataMember]
public string folder_id { get; set; }
[DataMember]
public string file_type_id { get; set; }
[DataMember]
public string prefix { get; set; }
[DataMember]
public fileInfo[] files;
[DataMember]
public termInfo[] terms;
}
[DataContract]
public class fileInfo
{
[DataMember]
public string name { get; set; }
[DataMember]
public string size { get; set; }
}
[DataContract]
public class termInfo
{
[DataMember]
public string term_id { get; set; }
[DataMember]
public string value { get; set; }
}
I have tried ServiceStack.Text, NewtonSoft.Json, and DataContractJsonSerializer. I get different results from each library, and none of them preserve the order of the DataMembers. (ServiceStack doesn't even serialize all the DataMembers.)
Passing the same InfoRequest object to each library, I get these strings:
JsonConvert:
{
"files":[
{
"name":"Blip.txt",
"size":"448"
},
{
"name":"blip.jpg",
"size":"71535"
}
],
"terms":[
{
"term_id":"1000",
"value":"Copyright"
},
{
"term_id":"1000",
"value":"Copyright"
}
],
"folder_id":"11245",
"file_type_id":"234",
"prefix":"",
"ServiceStack":{
"folder_id":"11245",
"file_type_id":"234",
"prefix":""
},
"MS":{
"file_type_id":"234",
"files":[
{
"name":"Blip.txt",
"size":"448"
},
{
"name":"blip.jpg",
"size":"71535"
}
],
"folder_id":"11245",
"prefix":"",
"terms":[
{
"term_id":"1000",
"value":"Copyright"
},
{
"term_id":"1000",
"value":"Copyright"
}
]
}
}
I suspect the order of DataMembers should not matter, but I'm getting an error from the server, and think that this might be the issue.
Any insight would be appreciated...
回答1:
Note ServiceStack's JSON Serializer only serializers public properties by default, if you want to include public fields as well (e.g. so it serializers 'files' and 'terms' as well) you need to include:
ServiceStack.Text.JsConfig.IncludePublicFields = true;
DataMembers does affect serialization in ServiceStack which makes all fields opt-in, use IgnoreDataMember
if you want to opt-out.
来源:https://stackoverflow.com/questions/15372045/json-parsing-object-to-string-preserve-order-of-elements