asp.net mvc c# 中的 Json 序列化
本文关键字:Json 序列化 中的 net mvc asp | 更新日期: 2023-09-27 18:27:03
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);