[英]Newtonsoft.Json Deserialize Collection
A third party vendor has a series of endpoints I am consuming, they have the following structure: 第三方供应商拥有我正在使用的一系列端点,它们具有以下结构:
[
{
"Id" : 117,
"Name" : "Example"
},
{
"Id" : 118,
"Name" : "Sample"
},
]
I created an object structure: 我创建了一个对象结构:
public class RootObject<TType>
{
public TType[] ApiModels { get; set; }
}
public class Sample
{
public int Id { get; set; }
public string Name { get; set; }
}
But when I go to deserialize I do: 但是当我去反序列化时,我会做:
JsonConvert.DeserializeObject<RootObject<Sample[]>>(...);
I receive an error cannot deserialize the current JSON array? 我收到一个错误,无法反序列化当前JSON数组? Why?
为什么? If I do dynamic I can traverse fine, I assume I'm doing something stupid.
如果我做动态运动,我可以遍历一切,我认为我做的事情很愚蠢。
Update Error: 更新错误:
One or more errors occurred.
发生一个或多个错误。 (Cannot deserialize the current JSON array (eg [1,2,3]) into type because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.)
(无法将当前的JSON数组(例如[1,2,3])反序列化为类型,因为该类型需要JSON对象(例如{“ name”:“ value”})才能正确地反序列化。要解决此错误,请更改JSON JsonArrayAttribute设置为JSON对象(例如{“ name”:“ value”})或将反序列化的类型更改为数组,或者将实现集合列表的类型(例如ICollection,IList)(例如可以从JSON数组反序列化的List)。也可以添加到该类型以强制其从JSON数组反序列化。路径”,第1行,位置1。)
JSON arrays correspond to List<T>
in C#, so instead of serialising to RootObject<Sample[]>
, you should serialise to List<Sample>
: JSON数组对应于C#中的
List<T>
,因此,应序列RootObject<Sample[]>
List<Sample>
,而不是序列RootObject<Sample[]>
List<Sample>
:
JsonConvert.DeserializeObject<List<Sample>>(...);
Using RootObject<Sample[]>
here is wrong because: 在这里使用
RootObject<Sample[]>
是错误的,因为:
RootObject<Sample[]>
would have a ApiModels
property of type Samples[][]
, which is obviously not what you want. RootObject<Sample[]>
将具有类型为Samples[][]
的ApiModels
属性,这显然不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.