尝试反序列化此JSON:
{ "result":"success" "arguments": { "activeTorrentCount":22, "cumulative-stats": { "downloadedBytes":1111, } } }
我的课:
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; } } }
我猜因为它在我的班级中具有cumulative_stats变量名称,所以不会反序列化accurate-stats,如何用破折号反序列化那个东西?
一种替代方法是使用DataContractJsonSerializer而不是JavascriptSerializer。
如果您这样声明类:
[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; } } }
您可以像这样反序列化:
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);
将产生: Cumulative-stats.downloadedBytes: 1111
Cumulative-stats.downloadedBytes: 1111