问题
Trying to deserialize this JSON:
{
"result":"success"
"arguments": {
"activeTorrentCount":22,
"cumulative-stats": {
"downloadedBytes":1111,
}
}
}
My class:
private class DeserializationMain
{
public string result; //works
public args arguments; //works, has deserialized activeTorrentCount
public class args
{
public int activeTorrentCount;
public current cumulative_stats; //doesn't work, equals null
public class current
{
public long downloadedBytes;
}
}
}
I guess cumulative-stats doesn't get deserialized because it has cumulative_stats variable name in my class, how to deserialize that thing with a dash?
回答1:
One alternative is to use the DataContractJsonSerializer instead of the JavascriptSerializer.
If you declare your classes like this:
[DataContract]
private class DeserializationMain
{
[DataMember(Name = "result")]
public string result; //works
[DataMember(Name = "arguments")]
public args arguments; //works, has deserialized activeTorrentCount
[DataContract]
public class args
{
[DataMember(Name = "activeTorrentCount")]
public int activeTorrentCount;
[DataMember(Name = "cumulative-stats")]
public current cumulative_stats; //doesn't work, equals null
[DataContract]
public class current
{
[DataMember(Name = "downloadedBytes")]
public long downloadedBytes;
}
}
}
You can deserialize it like this:
string json = "{\"result\":\"success\" , \"arguments\": { \"activeTorrentCount\":22, \"cumulative-stats\": { \"downloadedBytes\":1111 } } }";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DeserializationMain));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DeserializationMain result = serializer.ReadObject(ms) as DeserializationMain;
Console.WriteLine("Cumulative-stats.downloadedBytes: "+result.arguments.cumulative_stats.downloadedBytes);
Will produce:
Cumulative-stats.downloadedBytes: 1111
回答2:
I think most of the JSON serialization libraries support alias for properties, like custom attribute:
public class SomeClass {
[JsonProperty("cumulative-stats")]
public int CumulativeStats;
}
My suggestion is, keep your C# code with standard C# coding conventions and mapping to the property name in JSON.
来源:https://stackoverflow.com/questions/7494280/javascriptserializer-how-to-deserialize-a-property-with-a-dash-in-its-n