Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a Json Array in to a class in c#

I parsed this single Json :

{
    "text": "Sample Text",
    "id": 123456789,
    "user": {
      "name": "ExampleUser",
      "id": 123,
      "screen_name": "ExampleUser"
    },
    "in_reply_to_screen_name": null,
  }

to my c# class RootObject :

public class User
{
    public string name { get; set; }
    public int id { get; set; }
    public string screen_name { get; set; }
}

public class RootObject
{
    public string text { get; set; }
    public long id { get; set; }
    public User user { get; set; }
    public object in_reply_to_screen_name { get; set; }
}

like this :

RootObject h = JsonConvert.DeserializeObject<RootObject>(string);

All of this worked perfectly, but now I would like to parse an Array of all the precedent json object.

For example this Json Array :

[
    {
    "text": "Sample Text",
    "id": 123456789,
    "user": {
      "name": "ExampleUser",
      "id": 123,
      "screen_name": "ExampleUser"
    },
    "in_reply_to_screen_name": null,
  },
     {
    "text": "Another Sample Text",
    "id": 101112131415,
    "user": {
      "name": "ExampleUser2",
      "id": 124,
      "screen_name": "ExampleUser2"
    },
    "in_reply_to_screen_name": null,
  }
] 

I create another class :

  public class ListRoot { 
      public List<RootObject> status { get; set; } 
  }

and then used the same method :

ListRoot h = JsonConvert.DeserializeObject<ListRootObject>(string);

But it does not work. Do you know how can I parse this Json array to a c# class?

like image 886
user2505650 Avatar asked Dec 07 '13 20:12

user2505650


1 Answers

The JSON you have will work if you simply deserialize it as a List<RootObject>:

var h = JsonConvert.DeserializeObject<List<RootObject>>(string);

Or an array:

var h = JsonConvert.DeserializeObject<RootObject[]>(string);

If you want to deserialize a ListRoot, the JSON would need to look like this:

{
    "status": [
        {
            "text": "Sample Text",
            ...
        },
        {
            "text": "Another Sample Text",
            ...
        }
    ] 
}
like image 61
p.s.w.g Avatar answered Sep 30 '22 22:09

p.s.w.g