问题
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