使用 Newtonsoft 使用嵌套和可变字典解析 Json

时间:2021-03-25 14:28:06

标签: c# json dictionary parsing json.net

我有一个看起来像这样的 Json:

{
    "id": "1367",
    "title": "ticket sample",
    "custom_fields": {
        "13084": {
            "E0D4ED43": "South"
        },
        "13085": {
            "F19DF0D6": "Atlanta"
        },
        "13089": {
            "AF0EC62F": "Peter Johnson"
        }
    }
}

为了解析它,我的类使用嵌套字典:

class incident
    {
        public string id { get; set; }
        public string title { get; set; }
        public Dictionary<int, Dictionary<string, string>> custom_fields { get; set; }
    }

这很有效,直到我发现自定义字段并不总是相同的,例如我可以收到:

{
    "id": "1367",
    "title": "ticket sample",
    "custom_fields": {
        "13084": {
            "E0D4ED43": "South"
        },
        "13085": {
            "F19DF0D6": "Atlanta"
        },
        "13086": "SAP",
        "13088": {
            "AE3ED01A": "Commercial"
        }
    }
}

如果您查看自定义字段“13086”,它不包含另一个对象(它只是一个字符串),因此当我尝试使用前一个类进行解析时,它会失败。

这些是两种不同响应的示例,但是收到的密钥变化很大(这就是我使用字典的原因,因为我不知道每张票会收到多少和哪些)

1 个答案:

答案 0 :(得分:0)

感谢大家的评论。多亏了他们,我才弄清楚并找到了适合我的解决方案。

基本上,我使用了@DilshodK 提出的“Dictionary”,然后检查对象的类型。如果对象是 JObject,我用另一个字典重新反序列化,如果不是,我使用原始值。

class incident_custom
    {
        public string id{ get; set; }
        public string title { get; set; }
        public Dictionary<int, object> custom_fields { get; set; }
    }
incident_custom item = JsonConvert.DeserializeObject<incident_custom>(responseBody);

Console.WriteLine(item.title);

foreach (var field in item.custom_fields)
{
    if (field.Value.GetType() == typeof(Newtonsoft.Json.Linq.JObject))
    {

        Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(field.Value.ToString());

        foreach (var value in values)
        {
            Console.WriteLine(field.Key + " - " + value.Value);
        }
    }
    else
    {
        Console.WriteLine(field.Key + " - " + field.Value);
    }
}