Deserialzation from JSON file with multiple objects in C#

1 c# parsing json json.net

I have a JSON-file people.json containing multiple objects that I want to parse to a list People containing Person objects but with no luck. I get null from peopleLis and I suspect that I do something (probably a lot) wrong here. Can you guys help me out?

{
    "Andrew": {
        "weight": "75",
        "height": "181"
    },
    "Nathalie": {
        "weight": "68",
        "height": "182"
    },
    "Dave": {
        "weight": "83",
        "height": "192"
    }
}
Run Code Online (Sandbox Code Playgroud)

This is the code I tried out:

        public class Person
        {
            public int weight { get; set; }
            public int height { get; set; }
        }

        public class People
        {
            public List<Person> people { get; set; }
        }

        static void Main(string[] args)
        {
            People peopleList = JsonConvert.DeserializeObject<People>(File.ReadAllText(@"C:\people.json"));
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

您的 JSON 并不代表人员列表- 它代表具有多个属性的单个对象,其中每个属性值都是一个人。

您可以将其反序列化为Dictionary<string, Person>

string json = File.ReadAllText(@"C:\people.json");
var people = JsonConvert.DeserializeObject<Dictionary<string, Person>>(json);
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以从中创建一个列表(例如people.Values.ToList()),但您不应依赖于该列表的顺序与 JSON 文件中的顺序相同 - 从根本上来说,JSON 对象属性并不打算对顺序敏感。鉴于该人的名字可能很重要,我会坚持使用字典,其中每个条目的键是名字。

(作为旁注,我建议使用属性的惯用名称 soWeightHeight,然后[JsonProperty]根据需要使用 来指定 JSON 名称。)