解析动态命名的JSON对象的最有效方法是什么?
我正在尝试解析一个JSON响应,其中包含一些我不太熟悉的东西,也没有经常在野外见过.
I'm trying to parse a JSON response that includes something I'm not quite familiar with, nor have I seen in the wild that often.
在其中一个JSON对象中,有一个动态命名的JSON对象.
在此示例中,在"bugs"
中有一个名为"12345"
的JSON对象,该对象与错误编号相关.
In this example, there is a JSON object inside "bugs"
named "12345"
which correlates to a bug number.
{
"bugs" : {
"12345" : {
"comments" : [
{
"id" : 1,
"text" : "Description 1"
},
{
"id" : 2,
"text" : "Description 2"
}
]
}
}
}
我很好奇的是:解析这样一个动态命名的JSON对象的最有效方法是什么?
给出一些JSON Utility工具,例如
Given some JSON Utility tools like
- http://jsonutils.com/
- http://json2csharp.com/
他们将像上面的那样接受一个JSON响应,并按如下方式将其转换为类似以下的类:
They will take a JSON response like the one above and morph it into classes like the following respectfully:
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; }
}
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; }
}
与此有关的问题是,它会生成带有动态名称的class
.因此,使用该API的其他标识符进行的后续查询将导致失败,因为该名称不匹配,生成的[JsonProperty("")]
也将不匹配,因为按照上面生成的示例,该名称将包含动态类名.
The problem about this is that it generates a class
with a dynamic name. Thus subsequent queries with other identifiers to this API would result in a failure because the name does not match up nor would a generated [JsonProperty("")]
as it would contain the dynamic class name as per the generated examples above.
尽管JSON有效,但这似乎是以这种方式格式化的JSON的局限性.不幸的是,我对此JSON API没有任何控制权,所以我很好奇解决此问题的最佳方法是什么?
Although the JSON is valid, this seems to be a limitation with JSON that is formatted this way. Unfortunately I do not have any control on this JSON API, so I'm curious what the best way to approach this problem would be?
Newtonsoft.Json 将其解析为Dictionary<String, Comments>
,并提供适当的模型类:
Newtonsoft.Json JsonConvert can parse it as a Dictionary<String, Comments>
provided with appropriate model classes:
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; }
}
可以通过以下方式进行检查:
That can be checked with:
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);