简体   繁体   中英

Parsing Json with Newtonsoft getting error

On a web service call i get the following response

   {
   "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"
   }
}

I created a class to hold data

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

and tried to parse the json as follows

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>));

But getting the error

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

How can i fix this please help..

Your JSON element is an object, as it's delimited by { } , not an array which would be delimited by [ ] . So you can't just deserialize it into a List .

Your object has key-value pairs, string being the key and your LikeCount being the value. As such, you should deserialize it to an IDictionary<string, LikeCount> :

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

If you only need a list of your LikeCount objects without the keys, you can then get them using the 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();

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