【问题标题】:Access an array inside an object using Newtonsoft使用 Newtonsoft 访问对象内的数组
【发布时间】:2021-12-16 10:48:26
【问题描述】:

请查看下面的 JSON,我已使用 https://jsonlint.com/ 进行了验证:

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

我正在尝试将此 JSON 反序列化为这样的类:

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

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 这是我在上面得到的错误:“Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型'Person',因为类型需要一个 JSON 对象(例如 {"name":"value"})才能正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"...
    • @w0051977 你的课程有错误,使用我的课程来避免错误
    • 忽略我最后的评论。您的代码有效 - 谢谢。 +1 以获得全面的答案。
    • @w0051977 不客气
    猜你喜欢
    • 2013-04-28
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多