在asp.net c#中解析奇怪的Json
本文关键字:Json asp net | 更新日期: 2023-09-27 18:07:33
我正在调用一个api,它返回下面提到的json。
{
"salarySlipItems" : {
"'"0'"" : {
"value" : "11000.00",
"description" : "Worth Salary",
"sort" : "1"
},
"'"2'"" : {
"value" : "500.00",
"description" : "Other Income",
"sort" : "3"
},
"'"3'"" : {
"value" : "1354.84",
"description" : "General Allowance",
"sort" : "4"
},
"'"4'"" : {
"value" : "500.00",
"description" : "Telephone Allowance",
"sort" : "5"
},
"'"7'"" : {
"value" : "-2000.00",
"description" : "Other Deductions",
"sort" : "8"
}
},
"decimalDigits" : "2",
"status" : "1"
}
谁能指导我如何在c# asp.net中解析它?我相信的是salarySlipItems是一个具有所有属性的对象。'"0' '"'"2'等等是什么?
'"2'"
在本例中是字典的键。它只是一个转义的"2"
。在JSON响应中,由于某种原因,所有数字都以字符串的形式呈现。
你可以使用Dictionary
来反序列化这个JSON对象:
public class Response
{
public Dictionary<string, SlipItem> salarySlipItems { get; set; }
public string decimalDigits { get; set; }
public string status { get; set; }
}
public class SlipItem
{
public string value { get; set; }
public string description { get; set; }
public string sort { get; set; }
}
然后,你可以这样访问它:
var response = JsonConvert.DeserializeObject<Response>(jsonString);
Console.WriteLine(response.status);
按键访问字典项:
var item = response["'"2'""];
Console.WriteLine(item.value);
通过字典枚举:
foreach (var item in response)
{
Console.WriteLine("{0} has a description: {1}", item.Key, item.Value.description);
}