2012-03-07 18 views
3
public ActionResult About() 
{ 
List listStores = new List(); 
listStores = this.GetResults(「param」); 
return Json(listStores, 「Stores」, JsonRequestBehavior.AllowGet); 
} 

使用上面的代碼中,我能得到以下結果:JSON序列在asp.net mvc的C#

[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555", 
    "email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}}, 
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454", 
"email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}}, 

我將如何能得到以下結果格式?在結果的開始將需要商店。

{ 
"stores" : [ 
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555", 
    "email":"[email protected]", 
    "geo":{"latitude":"12.9876","longitude":"122.376237"}}, 
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454", 
    "email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237" 
}} ] } 
+0

有你爲什麼需要'stores'什麼特別的原因作爲對象的第一個成員? – 2012-03-07 02:37:11

回答

8

嘗試

return Json(new { stores = listStores }, JsonRequestBehavior.AllowGet); 

在上面的語句中,要創建一個名爲「商店」的屬性,然後從列表項的數組填充一個新的對象。

你也可以使用一個類,定義的東西,像這樣:

[DataContract] 
public class StoreListJsonDTO 
{ 
    [DataMember(Name = "stores")] 
    public List Stores { get; set; } 

    public StoreListJsonDTO(List storeList) 
    { 
     this.Stores = storeList; 
    } 
} 
在你的代碼

然後,你會怎麼做:

var result = new StoreListJsonDTO(listStores); 
return Json(result, JsonRequestBehavior.AllowGet); 
+0

可以說我想將「商店」的名稱更改爲序列化屬性等其他內容。 – pili 2012-03-07 02:45:14

+0

我想在未來將「商店」更改爲其他某個名稱。有沒有辦法讓我把它當作屬性?像DataContract pili 2012-03-07 02:50:31

+0

嗯,是的,你可以創建一個具有保存列表的屬性的類,然後使用必要的屬性([DataContract]類,然後[DataMember(Name =「Whatever_you_want」)]裝飾該屬性 – Chris 2012-03-07 03:06:17