问题
I am using an API from a 3rd-party that returns different JSON results from the same endpoint depending on how many results there are. If there is a single result the response is:
{
"data": {
...
},
"metadata": {
...
}
}
However if the result has more than one the response is:
{
"items": [{
"data": {...},
"metadata": {...}
}, {
"data": {...},
"metadata": {...}
}],
"metadata": {...}
}
I'm using C# and Json.Net and can't work out how to dynamically handle this mixed response. Is there a way to deserialize these responses with Json.net?
回答1:
Why not write something like this:
public class root
{
public Item data { get; set; }
public IList<Item> items { get; set; }
public MetaData metadata { get; set; }
}
And then check whether items
or data
is null when processing
回答2:
JSON.net has the JObject related classes that are handy for being a little less rigid and a bit more dynamic in nature. This allows you to (for instance):
var item = JObject.Parse(jsonText);
var hasItems = item.Properties().Any(p => p.Name == "items");
if(hasItems)
{
var items = item["items"].Select(t => t.ToObject<SomeClass>());
}
else
{
var sc = item.ToObject<SomeClass>();
}
来源:https://stackoverflow.com/questions/35329090/deserialize-json-that-could-be-an-array-or-a-single-item