使用 Newtonsoft 访问对象内的数组
Access an array inside an object using Newtonsoft
请参阅下面的 JSON,我已使用 https://jsonlint.com/:
对其进行了验证
{
"People": {
"data": [{
"id": "1",
"name": "Bert"
},
{
"id": "2",
"name": "Brian"
},
{
"id": "3",
"name": "Maria"
}
]
}
}
我正在尝试将此 JSON 反序列化为 class,如下所示:
public class Person
{
public string id;
public string name
}
到目前为止我试过这个:
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();
}
试试这个
var jsonDeserialized= JsonConvert.DeserializeObject<Root>(json);
List<Person> persons=jsonDeserialized.People.Persons;
如果您只需要一份人员名单,则只需一行
List<Person> persons = jsonConvert.DeserializeObject<Root>(json).People.Persons;
输出
1 Bert
2 Brian
3 Maria
类 ,你需要使用 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; }
}
请参阅下面的 JSON,我已使用 https://jsonlint.com/:
对其进行了验证{
"People": {
"data": [{
"id": "1",
"name": "Bert"
},
{
"id": "2",
"name": "Brian"
},
{
"id": "3",
"name": "Maria"
}
]
}
}
我正在尝试将此 JSON 反序列化为 class,如下所示:
public class Person
{
public string id;
public string name
}
到目前为止我试过这个:
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();
}
试试这个
var jsonDeserialized= JsonConvert.DeserializeObject<Root>(json);
List<Person> persons=jsonDeserialized.People.Persons;
如果您只需要一份人员名单,则只需一行
List<Person> persons = jsonConvert.DeserializeObject<Root>(json).People.Persons;
输出
1 Bert
2 Brian
3 Maria
类 ,你需要使用 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; }
}