0

I try to deserialize json and write to List

Here is my ViewModel code

public async void Posts_download()
    {
        string url = "https://www.reddit.com/top/.json?count=50";

        var json = await FetchAsync(url);
        var json_new = json.ToString();

        List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);

        PostsList = new List<RootObject>(rootObjectData);

    }
    private async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        return jsonString;
    }

And here is json response

JSON

I Have this error

enter image description here

How I can handle it?

UPDATE

Here is clases that I generate from json responce

Classes

Logan
  • 121
  • 13

2 Answers2

1

That JSON doesn't return an array. The RootObject should look like this:

public class RootObject
{
    public string kind { get; set; }
    public Data data { get; set; }
}

Then call it without the List<>:

RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);

In data there is a List<Child> children. I guess you were looking for that one. Please refer to Easiest way to parse JSON response to see how to create the C# objects.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

The json you posted isn't an array, its a json object, however you are asking jsonconvert to deserialize to an array. Change your RootObject class and add the other classes to:

class RootObject
{
    string kind {get;set}
    Data data {get;set;}
    List<Child> {get;set;}
}

class Data
{
    string modhash {get;set;}
    string before {get;set;}
    string after {get;set;}
}

class Child
{
    string kind {get;set;}
    data .. and so on.

}

Then you would change your jsonconver line to:

RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);

Please note this isn't a fully working example because it would have been cumbersome to fully define the Child class as there are many properties.

The reason this is needed is because the json posted was a json object that held an array. You can tell becuase the json started with "{", if it was an array it would have started with a "["

Steve
  • 502
  • 3
  • 12