'System.InvalidCastException : Unable to cast object of type 'SimpleJson.JsonArray' to type 'System.Collections.Generic.IDictionary [closed]

I am trying to deserialize https://jsonplaceholder.typicode.com/comments?postId=1 And check the number of comments returned from Json body. I am working in C# Xunit,please help.



Solution 1:[1]

Using Newtonsoft.Json (you can install through NuGet) you can deserialize the Json and do whatever you want with the data.

First, create your Post class:

public class Post
{
    public int PostId { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Body { get; set; }
}

Then, deserialize:

const string json = @"[{
    'postId': 1,
    'id': 1,
    'name': 'id labore ex et quam laborum',
    'email': '[email protected]',
    'body': 'laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium'
}]";

var posts = JsonConvert.DeserializeObject<List<Post>>(json);
var numberOfComments = posts.Count;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor