处理JSON数字变量
本文关键字:变量 数字 JSON 处理 | 更新日期: 2023-09-27 17:50:51
你好,我有这样的JSON:
ratings_total: {
1: "1",
2: 0,
3: 0,
4: 0,
5: "3"
}
如何在c#类中声明数值变量?
[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);