使用Json.net将JSON数组中的多个项添加到C#中的对象

时间:2011-01-20 20:50:11

标签: c# json.net deserialization

有谁能告诉我如何反序列化包含多个属性的对象?

鉴于下面的场景,代码工作正常。

public ActionResult Index()
{
    string json = @"{""name"": ""Person 2"",""email"": ""example@example.com""}";

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

但如果数组包含多个项目,我该怎么办,例如

string json = @"{""data"": [{""name"": ""Person 1"",""email"": ""test@test.com""},{""name"": ""Person 2"",""email"": ""example@example.com""}]}";

提前致谢

下面给出的答案对于我提出的问题是完美的,但现在我已经领先一步了。任何人都可以告诉我,如果json中有一个数组,我需要做什么,例如在?

中添加地址
{
    "data": [
        {
            "name": "Person 1",
            "email": "test@test.com",
            "address": {
                "address1": "my address 1",
                "address2": "my address 2" 
            } 
        },
        {
            "name": "Person 2",
            "email": "example@example.com",
            "address": {
                "address1": "my address 1",
                "address2": "my address 2" 
            } 
        } 
    ] 
}

3 个答案:

答案 0 :(得分:5)

过去这样的事情对我有用:

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

您可能需要按如下方式装饰Person对象:

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

答案 1 :(得分:3)

您可以使用匿名类型。

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

答案 2 :(得分:1)

反序列化为:

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