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? 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 arrays correspond to List<T>
in C#, so instead of serialising to RootObject<Sample[]>
, you should serialise to List<Sample>
:
JsonConvert.DeserializeObject<List<Sample>>(...);
Using RootObject<Sample[]>
here is wrong because:
RootObject<Sample[]>
would have a ApiModels
property of type Samples[][]
, which is obviously not what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.