【问题标题】:Strange Json to be parse in asp.net c#在asp.net c#中解析奇怪的Json
【发布时间】:2015-11-05 00:24:37
【问题描述】:

正在调用返回下面提到的 json 的 api。

{
    "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\等等..?

【问题讨论】:

标签: c# asp.net


【解决方案1】:

\"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);
}

【讨论】:

  • Response 还需要decimalDigitsstatus
  • @Rob 是的,刚刚注意到 :) 更新了。
  • 扩展@Yeldar 的答案 - 这只是一个普通的 JSON 对象,其属性恰好有一个数字作为其名称。由于 JSON 对象本质上只是哈希表/字典,而 C# 不允许属性以数字开头,因此您需要使用字典对其进行反序列化。
猜你喜欢
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多