我有一个对象,我正在转换为JSON以供Ember.js使用。
目前我有一些完全扩展但是ember期望的子对象
只是客户端的一组ID。如何将对象展平为
是int[]
items = Mapper.Map<IList<Item>>(client.GetItems());
foreach (var item in items)
{
int[] choices = item.Choices.Select(x => x.Id).ToArray();
item.Choices = choices;
}
收到有关无法从int[]
转换为IList<Item>
类型的错误
我该如何施展财产?
序列化后生成的当前JSON示例
{ "items": [
{
"id": 0,
"name": "Item0",
"description": "...",
"choices": [
{ "id": 0, "property": "somevalue" },
{ "id": 1, "property": "somevalue" },
]
},
{
"id": 1,
"name": "Item1",
"description": "...",
"choices": [
{ "id": 0, "property": "somevalue" },
{ "id": 1, "property": "somevalue" },
]
}
]}
我想制作的JSON
{ "items": [
{
"id": 0,
"name": "Item0",
"description": "...",
"choices": [0, 1]
},
{
"id": 1,
"name": "Item1",
"description": "...",
"choices": [0, 1]
}
]}
答案 0 :(得分:4)
SelectMany
展开列表列表并生成包含所有项目的单个列表。
items.SelectMany(x=>x.Choices.Select(y=>y.Id).ToArray()));
答案 1 :(得分:1)
得到一个关于无法从IList转换为int []类型的错误如何转换属性?
您无法将一种类型转换为另一种类型。相反,您可以在类中创建另一个int []类型的属性,并在getter中使用LINQ语句(带有必要的验证检查)。
public int[] ChoiceIDs
{
get {
return this.Choices.Select(x => x.Id).ToArray();
}
}