Deserialize JSON that could be an array or a single item

[亡魂溺海] 提交于 2019-12-12 03:25:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!