我这样做:我可以获得JavaScriptSerializer以分层序列化LINQ结果吗?
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;
}