我在做这个:
var data = from a in attributes
from i in attributeItems.Where(x=>x.DocClassAttributeFieldId == a.Id )
.DefaultIfEmpty(new DocClassAttributeFieldItem())
select new
{
Id = a.Id,
LabelText = a.LabelText,
Items = i
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
TextBox1.Text = serializer.Serialize(data);
结果是:
[{
"Id": 1,
"LabelText": "Unit On-Line Status:",
"Items": {
"Id": 1,
"DocClassAttributeFieldId": 1,
"LabelText": "Online",
"ValueText": "Online",
"Ordering": 1
}
},
{
"Id": 1,
"LabelText": "Unit On-Line Status:",
"Items": {
"Id": 2,
"DocClassAttributeFieldId": 1,
"LabelText": "Offline",
"ValueText": "Offline",
"Ordering": 2
},
}]
我想要这样的结果:
[{
"Id": 1,
"LabelText": "Unit On-Line Status:",
"Items": [{
"Id": 1,
"DocClassAttributeFieldId": 1,
"LabelText": "Online",
"ValueText": "Online",
"Ordering": 1
},{
"Id": 2,
"DocClassAttributeFieldId": 1,
"LabelText": "Offline",
"ValueText": "Offline",
"Ordering": 2
}]
}]
这可以用JavaScriptSerializer轻松完成吗?或者可以重新编写LINQ语句来生成它吗?
更新:感谢一些类似的帖子。。。
http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
http://encosia.com/using-complex-types-to-make-calling-services-less-complex/
我不打算使用JavaScriptSerializer,ASP.Net为我做这一切:
[WebMethod]
public static object GetDocClass(int docClassId)
{
var data = from a in attributes
select new
{
Id = a.Id,
LabelText = a.LabelText,
Items = attributeItems.Where(x=>x.DocClassAttributeFieldId == a.Id)
};
return data;
}
您可以这样做,但需要使用group来填充项目。
var data =
from a in attributes
from i in attributeItems.Where(x=>x.DocClassAttributeFieldId == a.Id )
group a by a.Id, a.LabelText into myGroup
.DefaultIfEmpty(new DocClassAttributeFieldItem())
select new
{
Id = a.Id,
LabelText = a.LabelText,
Items = myGroup.ToList()
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
TextBox1.Text = serializer.Serialize(data);
这是一个臀部注射,所以如果它对你不起作用,请告诉我。
可能有更好的方法,但Nix的回答帮助我想出了这个:
var data = from a in attributes
select new
{
Id = a.Id,
LabelText = a.LabelText,
Items = attributeItems.Where(x=>x.DocClassAttributeFieldId == a.Id)
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
TextBox1.Text = serializer.Serialize(data);