使用 Newtonsoft 解析 Json 时出错

Parsing Json with Newtonsoft getting error

在 Web 服务调用中,我收到以下响应

   {
   "132800000000040": {
      "likes": 38347,
      "id": "132800000000040"
   },
   "192011111111130": {
      "likes": 44855,
      "id": "192011111111130"
   },
   "115372222222226": {
      "likes": 42227,
      "id": "115372222222226"
   },
   "186111111111116": {
      "likes": 21987,
      "id": "186111111111116"
   },
   "30000000002": {
      "likes": 18539,
      "id": "30000000002"
   },
   "24000000006": {
      "likes": 16438,
      "id": "24000000006"
   }
}

我创建了一个 class 来保存数据

public class LikeCount
{
    public string id { get; set; }
    public string likes { get; set; }
}

并尝试按如下方式解析 json

var responseString = await response.Content.ReadAsStringAsync();
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString);
List<LikeCount> LikeList = (List<LikeCount>)Newtonsoft.Json.JsonConvert.DeserializeObject(obj.ToString(), typeof(List<LikeCount>));

但是出现错误

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Rxz.Model.LikeCount]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

我该如何解决这个问题,请帮忙..

您的 JSON 元素是一个对象,因为它由 { } 分隔,而不是一个由 [ ] 分隔的数组。所以你不能把它反序列化成 List.

您的对象具有键值对,string 是键,您的 LikeCount 是值。因此,您应该将其反序列化为 IDictionary<string, LikeCount>:

IDictionary<string, LikeCount> dict = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, LikeCount>>(responseString);

如果您只需要 LikeCount 对象的列表而不需要密钥,则可以使用 Values property. Then, depending on your needs, you may or may not need to convert it to a List via ToList:

获取它们
IDictionary<string, LikeCount> dict = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, LikeCount>>(responseString);
List<LikeCount> likes = dict.Values.ToList();