如何反序列化的JSON数组和QUOT;根"元素使用Json.NET在阵列中的每个对象? [英] How to deserialize JSON array with "root" element for each object in array using Json.NET?
问题描述
我有以下JSON字符串:
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);
}
是否有可能做 Json.NET 而无需创建包装类,像PersonResult?
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.
推荐答案
很遗憾,有没有什么可以做这个问题。这就是JSON格式的样子,并有周围没有办法。其结果是,Json.Net看到你的字符串作为或多或少:
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 withName
andGender
properties
你可能玩一些自定义 ContractResolvers 强制序列化工作方式不同......但是这是相当多的工作。像你所说的包装类是如何将这些问题的处理,我建议坚持它。
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.
这篇关于如何反序列化的JSON数组和QUOT;根&QUOT;元素使用Json.NET在阵列中的每个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!