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

前端 未结 2 1795
一向
一向 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:35

    Newtonsoft.Json JsonConvert can parse it as a Dictionary provided with appropriate model classes:

    public class Comment
    {
        public int id { get; set; }
        public string text { get; set; }
    }
    
    public class Comments
    {
        public List comments { get; set; }
    }
    
    public class RootObject
    {
        public Dictionary 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(json);
    
    Console.WriteLine(obj.bugs["12345"].comments.First().text);
    

提交回复
热议问题