【问题标题】:Unable to parse json into an object无法将 json 解析为对象
【发布时间】:2016-04-12 18:57:25
【问题描述】:

我不知道如何将以下 json 解析为强类型对象。

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
    },
}

问题是数字 71161 对于每个 JSON 响应可能不同。

【问题讨论】:

  • 如果你使用 JSON.parse(your_json_string); 会发生什么
  • @pantuofermo Json 是有效的并且会解析。但是如何将它变成强类型对象呢?
  • 您必须将data 定义为Dictionary<string, YourObjectData>
  • 哦,我明白你的意思了。我认为您想使用 Newtonsoft 的流行 Json.NET 库。您可以使用 nuget 下载它。引用该库后,您可以通过执行以下操作将 json 字符串转换为强类型对象:Movie m = JsonConvert.DeserializeObject(jsonString);
  • 连同 haim770 指出的内容和我的解决方案,这应该可以满足您的需求。

标签: c# json serialization json.net


【解决方案1】:

使用Json.NET from Newtonsoft。让data 属性为Dictionary<int, Item>,库将处理从string 到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"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多