我這樣做:我可以獲得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;
}