JavaScriptSerializer - 如何使用短划线(“ - ”)对其名称进行反序列化?

时间:2011-09-21 03:32:02

标签: c# .net json serialization javascriptserializer

尝试反序列化此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变量名,如何用破折号反序列化该东西?

2 个答案:

答案 0 :(得分:17)

另一种方法是使用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

答案 1 :(得分:4)

我认为大多数JSON序列化库都支持属性的别名,例如自定义属性:

public class SomeClass {
    [JsonProperty("cumulative-stats")]
    public int CumulativeStats;
}

我的建议是,保持C#代码符合标准C#编码约定并映射到JSON中的属性名称。