问题描述
我有给我类似的项目,如不同的对象而不是作为一个数组成员列表的API。让我们来看看在 _items 节点,它包含在存储中的可用项目:
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},
}
}
我使用的是非常好的Newtonsoft JSON.NET做我的反序列化,但我不知道我怎么能得到项目的列表。它的名单阵列,说:
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":...
我猜想,这本来是很容易使用JsonConvert获得
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.
。可惜我不能改变的API。
谢谢。
. Too bad I can't change the API.thanks.
推荐答案
您可以使用 JsonExtensionDataAttribute
来存储项目,并使用一个属性将它们转换为项目
实例。
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>());
}
}
}
这篇关于反序列化JSON对象到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!