Deserializing JSON objects to an array

时光怂恿深爱的人放手 提交于 2019-12-13 03:59:36

问题


I have an API that gives me a list of similar items as different object instead that as members of an array. Let's see the _items node, which contains the available items on a store:

{
    "_ok":200,

    "_store":
          {
           "location":"Rome",
           "open":true
          },
    "_items":
         {
            "itemA":{ "color":"blue","size":3},
            "itemB":{ "color":"red","size":1},
            "itemC":{ "color":"cyan","size":3},
            "itemD":{ "color":"yellow","size":0},
          }

}

I am using the very nice Newtonsoft JSON.NET to do my deserialization, but I do not know how can I get a list of items. it the list was an array, say:

"_items":{["itemA":{ "color":"blue","size":3},"itemB":...

I guess that it would have been easy using JsonConvert to get a

List<Item> 

where Item was a class with color and size member.

. Too bad I can't change the API. thanks.


回答1:


You can use JsonExtensionDataAttribute to store the items, and use a property to convert them to Item instances.

[JsonProperty("_items")]
private ItemsContainer _items;


[JsonObject(MemberSerialization.OptIn)]
class ItemsContainer
{
    [JsonExtensionData]
    private IDictionary<string, JToken> _items;

    public IEnumerable<Item> Items
    {
        get
        {
            return _items.Values.Select(i => i.ToObject<Item>());
        }
    }
}


来源:https://stackoverflow.com/questions/20447558/deserializing-json-objects-to-an-array

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