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

Parsing Json with nested and variable dictionaries using Newtonsoft

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

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

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

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”,它不包含另一个对象(它只是一个字符串),所以当我尝试使用前面的 class 进行解析时,它失败了。

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

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

基本上,我使用了@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);
    }
}