【问题标题】:Json serialization in asp.net mvc c#asp.net mvc c#中的Json序列化
【发布时间】:2012-03-07 02:35:35
【问题描述】:
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"
}} ] }

【问题讨论】:

  • 有什么特殊原因需要stores 作为对象的第一个成员吗?

标签: c# asp.net-mvc json asp.net-mvc-3 c#-4.0


【解决方案1】:

试试

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

【讨论】:

  • 可以说我想将“商店”的名称更改为其他东西,例如序列化属性。
  • 我想将来将“Stores”更改为其他名称。请问有没有办法可以将它作为属性?像 DataContract
  • 嗯,是的,您可以创建一个具有保存列表的属性的类,并用必要的属性装饰该属性(类上的 [DataContract],然后是 [DataMember(Name = "Whatever_you_want ")] 属性本身。为了简洁起见,我只是给你一个匿名对象示例。
  • [DataMember(Name = "stores")] 当我将它作为 asp.net mvc 操作结果返回时不起作用
  • 啊,默认情况下 MVC3 使用 JavascriptSerializer。要使用 DataContract / DataMember 属性,您需要强制它使用 DataContractJsonSerializer,如下所述:stackoverflow.com/questions/1302946/…
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
相关资源
最近更新 更多