What is the most effective way to parse JSON objects that are dynamically named?

前端 未结 2 1796
一向
一向 2021-01-03 05:00

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.

Inside one of the JSON ob

相关标签:
2条回答
  • 2021-01-03 05:08

    Try Json.NET, available as a Nuget package (Newtonsoft.Json) or from http://www.newtonsoft.com/json.

    Json.NET can perform class-based serialization/deserialization such as you show. It also provides a generic JObject and JToken classes for cases where the format of the Json is not known or not fixed at dev time.

    Here's an example loading a json object from a file.

    // load file into a JObject
    JObject document;
    using (var fileStream = File.OpenRead(someFilePath))
    using (var streamReader = new StreamReader(fileStream))
    using (var jsonReader = new JsonTextReader(streamReader))
        document = JObject.Load(jsonReader);
    
    // read the JObject
    var bugs = (JObject) document["bugs"];
    foreach (var bugEntry in bugs)
    {
        var bugID = bugEntry.Key;
        var bugData = (JObject) bugEntry.Value;
        var comments = (JArray) bugData["comments"];
        foreach (JObject comment in comments)
            Debug.Print(comment["text"]);
    }
    
    0 讨论(0)
  • 2021-01-03 05:35

    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);
    
    0 讨论(0)
提交回复
热议问题