Search code examples
c#arraysjson.netcontainersjson-deserialization

Deserialize a json container array


The data I am trying to Deserialize is exacly like this json in this post>

Deserialize JSON Facebook feed using Gson , Only with more objects, inside the container.. and i'm not using "Gson"

I think some of the objects even have their own containers nested somewhere, but that is not the issue at present, the main issue is that I am having problems deserializing into the following class..

public class Rootobject
{
    public int found { get; set; }
    public Post[] posts { get; set; }
    public Meta meta { get; set; }
}

I understand that the way the json from the API is layed out, it some sort of array, in the Json.net docs, they call it a DataSet.. I am using Json.Net

my most recent attempt to deserialize is;

List<Rootobject> data = JsonConvert.DeserializeObject<List<Rootobject>>(stringData);

But still data is null and I get;

Additional information:

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

perhaps LINQ to JSON is the way to go not sure as yet.. any suggestions?


Solution

  • The first thing is the JSON at the post is not a valid JSON string so it cannot be desearlized. Secondly I tried to rectify and correct the JSON to make it a valid JSON and thus your JSON looks like

    {
        "data": [
            {
                "id": "105458566194298_411506355589516",
                "message": "...",
                "type": "status",
                "created_time": "2012-11-25T17:26:41+0000",
                "updated_time": "2012-11-25T17:26:41+0000",
                "comments": {
                    "count": 0
                }
            },
            {
                "id": "105458566194298_411506355589516",
                "message": "...",
                "type": "status",
                "created_time": "2012-11-25T17:26:41+0000",
                "updated_time": "2012-11-25T17:26:41+0000",
                "comments": {
                    "count": 0
                }
            }
        ]
    }
    

    So the Classes structure would be something like this

    public class Comments
    {
        public int count { get; set; }
    }
    public class Datum
    {
        public string id { get; set; }
        public string message { get; set; }
        public string type { get; set; }
        public DateTime created_time { get; set; }
        public DateTime updated_time { get; set; }
        public Comments comments { get; set; }
    }
    public class MyData
    {
        public List<Datum> data { get; set; }
    }
    

    and then Desearlize it normally like you were doing

    MyData data = JsonConvert.DeserializeObject<MyData>(stringData);