0

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();
        }

1 Answer 1

1

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; }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is the error I get with the above: "Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Person' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"...
@w0051977 your classes are having bugs, use my classess to avoid the error
Ignore my last comment. Your code works - thanks. +1 for the comprehensive answer.
@w0051977 You are very welcome

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.