How to deserialize JSON array with “root” element for each object in array using Json.NET?

左心房为你撑大大i 提交于 2019-12-07 04:02:51

问题


I have following JSON string:

[
  { "Person" : { "Name" : "John", "Gender" : "male" } },
  { "Person" : { "Name" : "John", "Gender" : "male" } }
]

(As you may notice unfortunately I have a sort of "root" element for each object in the array. Without this "root" element the task becomes quite trivial.)

I have to deserialize it into a list of Person class:

class Person {
    public string Name { get; set; }
    public string Gender { get; set; }
}
...
List<Person> ListPersons() {
    return JsonConvert.DeserializeObject<List<Person>>(jsonString);
}

Is it possible to do with Json.NET without creating wrapper class like PersonResult?

class PersonResult {
    public Person Person { get; set; }
}
...
List<Person> ListPersons() {
    return JsonConvert.DeserializeObject<List<PersonResult>>(jsonString)
                      .Select(p => p.Person)
                      .ToList();
}

The perfect solution for me is to be able somehow explicitly specify this "root" (e.g. via attribute) and do not create any wrappers, helpers, etc.


回答1:


Unfortunatelly, there's not much you can do about this issue. That's how JSON format looks like and there's no way around that. As a result, Json.Net "sees" your string as more or less:

an array of objects with Person property, which is another object with Name and Gender properties

You could possibly play some with custom ContractResolvers to force serializer to work differently... but that's quite a bit of work. Wrapper class like you suggested is how those problems are dealt with, and I suggest sticking to it.



来源:https://stackoverflow.com/questions/8751570/how-to-deserialize-json-array-with-root-element-for-each-object-in-array-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!