简体   繁体   中英

Unable to parse json into an object

I am not sure how to parse the following json into a strongly typed object.

The JSON:

{
  "data": {
    "71161": {
      "air_by_date": 0,
      "anime": 0,
      "cache": {
        "banner": 1,
        "poster": 1
      },
      "indexerid": 71161,
      "language": "en",
      "network": "CBS",
      "next_ep_airdate": "",
      "paused": 0,
      "quality": "SD",
      "show_name": "name",
      "sports": 0,
      "status": "Ended",
      "subtitles": 0,
      "tvdbid": 71161
    },
    "71211": {
      "air_by_date": 0,
      "anime": 0,
      "cache": {
        "banner": 1,
        "poster": 1
      },
      "indexerid": 71211,
      "language": "en",
      "network": "ABC (US)",
      "next_ep_airdate": "",
      "paused": 0,
      "quality": "SD",
      "show_name": "name2",
      "sports": 0,
      "status": "Ended",
      "subtitles": 0,
      "tvdbid": 71211
    },
}

The issue is the number 71161 this can be different for each JSON response.

Use Json.NET from Newtonsoft . Let the data property be a Dictionary<int, Item> , the library will handle the conversion of keys from string to int :

class Program
{
    class Item
    {
        [JsonProperty(PropertyName = "status")]
        public string Status { get; set; }
    }
    class Root
    {
        [JsonProperty(PropertyName = "data")]
        public Dictionary<int, Item> Data { get; set; }
    }

    static void Main(string[] args)
    {
        var root = JsonConvert.DeserializeObject<Root>(@"{ ""data"": { ""123"": { ""status"": ""Ended"" } } }");
        Console.WriteLine(root.Data[123].Status); // prints "Ended"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM