处理JSON数字变量

时间:2014-03-19 08:13:56

标签: c# .net json

你好我有这样的JSON:

ratings_total: {
   1: "1",
   2: 0,
   3: 0,
   4: 0,
   5: "3"
}

我们如何在C#类中声明数字变量?

1 个答案:

答案 0 :(得分:0)

[DataContract]
class Foo
{
    [DataMember(Name = "ratings_total")]
    public Dictionary<int,int> RatingsTotal { get; set; }
}
var json = @"{
    ""ratings_total"": {
        ""1"": ""1"",
        ""2"": 0,
        ""3"": 0,
        ""4"": 0,
        ""5"": ""3""
    }
}";

// Convert string to a stream (only nessesary for this example)
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(json);
writer.Flush();
stream.Position = 0;

// Settings to enable dictionary serialization
var settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
var ser = new DataContractJsonSerializer(typeof(Foo), settings);

// Deserialize object
var obj = (Foo)ser.ReadObject(stream);