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

I have a JSON string:

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

(As you can see, unfortunately, I have my own “root” element for each object in the array. Without this “root” element, the task becomes quite trivial.)

I need to deserialize it into a class list Person:

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 a wrapper class such as PersonResult?

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

The ideal solution for me is to somehow explicitly specify this "root" (for example, through an attribute) and not create any wrappers, helpers, etc.

+5
source share
1 answer

, . , JSON, . Json.Net "" :

Person, Name Gender

, ContractResolvers, -... . Wrapper, , , , .

+4

All Articles