解析动态命名的JSON对象的最有效方法是什么?

Jon*_*las 5 c# json

我正在尝试解析一个JSON响应,其中包含一些我不太熟悉的东西,也没有经常在野外看到过.

在其中一个JSON对象中,有一个动态命名的JSON对象.

在此示例中,"bugs"命名中有一个JSON对象,"12345"它与一个错误号相关联.

{
   "bugs" : {
      "12345" : {
         "comments" : [
            {
               "id" : 1,
               "text" : "Description 1"
            },
            {
               "id" : 2,
               "text" : "Description 2"
            }
         ]
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我很好奇的是:解析动态命名的JSON对象最有效的方法什么?

给出了一些JSON Utility工具

他们会像上面那样采用JSON响应,并将其变为类似下面的类:

jsonutils

public class Comment
{
    public int id { get; set; }
    public string text { get; set; }
}

public class 12345
{
    public IList<Comment> comments { get; set; }
}

public class Bugs
{
    public 12345 12345 { get; set; }
}

public class Root
{
    public Bugs bugs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

json2charp

public class Comment
{
    public int id { get; set; }
    public string text { get; set; }
}

public class __invalid_type__12345
{
    public List<Comment> comments { get; set; }
}

public class Bugs
{
    public __invalid_type__12345 __invalid_name__12345 { get; set; }
}

public class RootObject
{
    public Bugs bugs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这个问题是它生成class一个动态名称.因此,具有该API的其他标识符的后续查询将导致失败,因为该名称不匹配也不会生成[JsonProperty("")],因为它将包含根据上面生成的示例的动态类名.

虽然JSON是有效的,但这似乎是JSON的限制,这种格式是这样设置的.不幸的是我对这个JSON API没有任何控制权,所以我很好奇解决这个问题的最佳方法是什么?

Eug*_*kal 3

Newtonsoft.Json JsonConvert可以将其解析Dictionary<String, Comments>为提供了适当的模型类:

public class Comment
{
    public int id { get; set; }
    public string text { get; set; }
}

public class Comments
{
    public List<Comment> comments { get; set; }
}

public class RootObject
{
    public Dictionary<String, Comments> bugs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

可以通过以下方式检查:

var json = "{\r\n   \"bugs\" : {\r\n      \"12345\" : {\r\n         \"comments\" : [\r\n            {\r\n               \"id\" : 1,\r\n               \"text\" : \"Description 1\"\r\n            },\r\n            {\r\n               \"id\" : 2,\r\n               \"text\" : \"Description 2\"\r\n            }\r\n         ]\r\n      }\r\n   }\r\n}";

Console.WriteLine(json);

var obj = JsonConvert.DeserializeObject<RootObject>(json);

Console.WriteLine(obj.bugs["12345"].comments.First().text);
Run Code Online (Sandbox Code Playgroud)