从MVC控制器返回Json数据

3
   public ActionResult About()
    {
        List<Stores> listStores = new List<Stores>();
        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
请在这方面帮助我。
4个回答

5
你需要创建一个对象,其中包含一个名为stores的属性,该属性内部存储商店的信息:
public ActionResult About()
{
    var result = new { stores = this.GetResults("param") };
    return Json(result, "Stores", JsonRequestBehavior.AllowGet);
}

为了简单起见,我在这里使用了匿名类型,如果需要在多个地方使用此结果类型,则可以考虑为其创建一个“适当”的类。


1

JavaScriptSerializer 可以在命名空间 System.Web.Script.Serialization 中找到。

var ser = new JavaScriptSerializer();
var jsonStores = ser.Serialize(stores);

return Json(new { stores: jsonStores }, "Stores", JsonRequestBehavior.AllowGet);

1
如果您想将对象以Json格式发送到客户端,例如Data-table,List,Dictionary等,则需要重写jsonResult和ExecuteResult。
否则,请使用linq格式返回数据
例如
使用JSON.NET(必须使用override jsonResult和ExecuteResult)
  DataTable dt = new DataTable();//some data in table
   return json("data",JsonConvert.SerializeObject(dt))

另一种选项是使用 Linq。

var Qry = (from d in dt.AsEnumerable()
                               select new
                               {
                                   value = d.Field<int>("appSearchID"),
                                   text = d.Field<string>("appSaveSearchName"),
                                   type = d.Field<int>("appSearchTypeStatus")
                               });
                     return json("Data", Qry);

覆盖方法
 protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            try
            {
                    return new JsonNetResult
                    {
                        Data = data,
                        ContentType = contentType,
                        ContentEncoding = contentEncoding,
                        JsonRequestBehavior = behavior,
                        MaxJsonLength = int.MaxValue
                    };

            }
            catch (Exception)
            {
                throw;
            }
        }

    public class JsonNetResult : JsonResult
        {
           public override void ExecuteResult(ControllerContext context)
            {
                try
                {
                HttpResponseBase response = context.HttpContext.Response;
                    response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
                    if (this.ContentEncoding != null)
                        response.ContentEncoding = this.ContentEncoding;
                    if (this.Data == null)
                        return;
                    using (StringWriter sw = new StringWriter())
                    {
                        response.Write(this.Data);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

尽管你的回答可能解决了问题,但请尝试解释为什么它可以解决问题。指出一些你所改变/修复的东西以使其正常工作。这将有助于提问者理解为什么你的回答可以解决他的问题。 - Mathlight

-1
public class StoresViewModel{
    public List<Stores> stores {get;set;}
}


public ActionResult About()
{
        List<Stores> listStores = new List<Stores>();
        listStores = this.GetResults("param");
        StoresViewModelmodel = new StoresViewModel(){
            stores = listStores;
        }
        return Json(model, JsonRequestBehavior.AllowGet);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接