JavaScriptSerializer - 如何反序列化的属性用破折号(QUOT; - ")在它的名字? [英] JavaScriptSerializer - how to deserialize a property with a dash ("-") in it's name?
本文介绍了JavaScriptSerializer - 如何反序列化的属性用破折号(QUOT; - ")在它的名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试反序列化此JSON:
Trying to deserialize this 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变量名在我的课,如何反序列化的东西有几许?
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?
推荐答案
一种选择是使用JavascriptSerializer的DataContractJsonSerializer代替。
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);
会产生:
累积stats.downloadedBytes 1111
Will produce:
Cumulative-stats.downloadedBytes: 1111
这篇关于JavaScriptSerializer - 如何反序列化的属性用破折号(QUOT; - ")在它的名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文