Roffers
Roffers

Reputation: 701

Add multiple items in JSON array to object in C# using Json.net

Can anyone tell me how I can deserialize an object that contains multiple attributes?

Given the scenario below, the code works fine.

public ActionResult Index()
{
    string json = @"{""name"": ""Person 2"",""email"": ""[email protected]""}";

    var emp = JsonConvert.DeserializeObject<Person>(json);
    Response.Write(emp.name + emp.email);
    return View();
}

public class Person
{
    public string name { get; set; }
    public string email { get; set; }
}

But what do I have to do if the array contains multiple items, e.g

string json = @"{""data"": [{""name"": ""Person 1"",""email"": ""[email protected]""},{""name"": ""Person 2"",""email"": ""[email protected]""}]}";

Thanks in advance

The answers already given below were perfect for the problem I asked, but now I've gone one step ahead. Can anyone advise on what I'd need to do if the json had an array in it e.g. the addition of an address in?

{
    "data": [
        {
            "name": "Person 1",
            "email": "[email protected]",
            "address": {
                "address1": "my address 1",
                "address2": "my address 2" 
            } 
        },
        {
            "name": "Person 2",
            "email": "[email protected]",
            "address": {
                "address1": "my address 1",
                "address2": "my address 2" 
            } 
        } 
    ] 
}

Upvotes: 5

Views: 19586

Answers (3)

Enigmativity
Enigmativity

Reputation: 117175

You could use an anonymous type.

var template = new { data = new Person[] { } };
Person[] emps = JsonConvert
    .DeserializeAnonymousType(json, template)
    .data;

Upvotes: 3

Guillaume86
Guillaume86

Reputation: 14384

deserialize as :

public class JsonData
{
  public List<Person> Data {get;set;}
}

Upvotes: 1

Chazmanian
Chazmanian

Reputation: 221

Something like this has worked for me in the past:

JObject o = JObject.Parse(json); // This would be the string you defined above
// The next line should yield a List<> of Person objects...
List<Person> list = JsonConvert.DeserializeObject<List<Person>>(o["data"].ToString());

You might want to decorate your Person object as follows:

[JsonObject(MemberSerialization.OptIn)]
public class Person
{
    [JsonProperty]
    public string name{get;set;}
    [JsonProperty]
    public string email{get;set;}
}

Upvotes: 5

Related Questions