您使用MVC 3? - 做這樣的事情:
return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
我用它來返回複雜的c#對象,匹配我想要的javascript對象的結構。
例如爲:
var bob = new {
name = "test"
,orders = new[] {
new { itemNo = 1, description = "desc"}
,new { itemNo = 2, description = "desc2"}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
給出:
{
"name":"test",
"orders":[
{
"itemNo":1,
"description":"desc"
},
{
"itemNo":2,
"description":"desc2"
}
]
}
編輯:一個有趣的一點嵌套:
var bob = new {
name = "test"
,
orders = new [] {
new { itemNo = 1, description = "desc"}
,new { itemNo = 2, description = "desc2"}
}
,test = new {
a = new {
b = new {
something = "testing"
,someOtherThing = new {
aProperty="1"
,another="2"
,theThird=new{
bob="quiteDeepNesting"
}
}
}
}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
給出:
{
"name":"test",
"orders":[
{
"itemNo":1,
"description":"desc"
},
{
"itemNo":2,
"description":"desc2"
}
],
"test":{
"a":{
"b":{
"something":"testing",
"someOtherThing":{
"aProperty":"1",
"another":"2",
"theThird":{
"bob":"quiteDeepNesting"
}
}
}
}
}
}
您是否使用JSON.Net庫或自定義實現?檢查圖書館是否可以提供幫助 - 將爲您節省大量時間... – Sunny 2012-04-27 16:11:15
您將什麼定義爲*嵌套字符串*? – 2012-04-27 16:13:02
@cWilk,你應該張貼您的代碼(預計1條或2號線),顯示創建JSON你選擇什麼特別的「非常容易」的方式。從SP – 2012-04-27 16:16:17