public ActionResult About()
{
List listStores = new List();
listStores = this.GetResults(“param”);
return Json(listStores, “Stores”, JsonRequestBehavior.AllowGet);
}
使用上面的代码我可以得到下面的结果:
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
"email":"abc@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
我怎样才能得到以下格式的结果?需要在结果的开头存储。
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555",
"email":"abc@ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454",
"email":"nfnf@ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"
}} ] }
最佳答案
尝试
return Json(new { stores = listStores }, JsonRequestBehavior.AllowGet);
在上面的语句中,您正在创建一个新对象,该对象具有名为“stores”的属性,然后用列表中的项目数组填充该对象。
你也可以使用类,定义如下:
[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);
关于c# - asp.net mvc c#中的Json序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595052/