Home > database >  Access an array inside an object using Newtonsoft
Access an array inside an object using Newtonsoft

Time:11-02

Please see the JSON below, which I have validated using https://jsonlint.com/:

{
        "People": {
            "data": [{
                    "id": "1",
                    "name": "Bert"
                },
                {
                    "id": "2",
                    "name": "Brian"
                },
                {
                    "id": "3",
                    "name": "Maria"
                }
            ]
        }
    }

I am trying to deserialize this JSON into a class like this:

 public class Person
    {
        public string id;
        public string name
    }

So far I have tried this:

public static List<Person> DeserializePeople(string json)
        {
            var jo = JObject.Parse(json);
            return jo["data"]["People"]
                .Select(s => new Person
                {
                    id = ((string)s[0] == null) ? "" : (string)s[0],
                    name = ((string)s[1] == null) ? "" : (string)s[1],
                })
                .ToList();
        }

CodePudding user response:

try this

var jsonDeserialized= JsonConvert.DeserializeObject<Root>(json); 

List<Person> persons=jsonDeserialized.People.Persons;

or just in one line if you only need a list of persons

List<Person> persons = jsonConvert.DeserializeObject<Root>(json).People.Persons;

output

    1   Bert
    2   Brian
    3   Maria

classes , you need to use getter /setter

public class Person
{
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class People
{ 
    [JsonProperty("data")]
    public List<Person> Persons { get; set; }
}

public class Root
{
    public People People { get; set; }
}
  • Related