反序列化可以是数组或单个项目的JSON [英] Deserialize JSON that could be an array or a single item
问题描述
我正在使用第三方提供的API,该API从同一个端点返回不同的JSON结果,具体取决于有多少结果.如果只有一个结果,则响应为:
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": {...}
}
我正在使用C#和Json.Net,无法解决如何动态处理此混合响应的问题.是否可以通过Json.net反序列化这些响应?
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?
推荐答案
JSON.net具有与JObject相关的类,这些类在本质上具有更少的刚性和更高的动态性,非常方便.这使您能够(例如):
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>();
}
这篇关于反序列化可以是数组或单个项目的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!