繁体   English   中英

asp.net中的json序列化mvc c#

[英]Json serialization in asp.net mvc c#

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM