JSON返回了数据格式

时间:2012-02-06 13:56:17

标签: asp.net asp.net-mvc json

我正在使用下面的代码来获取JSON数据:

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult getBranchViaJson()
    {
       Json(getBranchList(AppSession.BranchID.Value));
    }


    private object getBranchList(int n)
    {

        var mybranchList = from p in getBranchs(n)
                 select new { p.Code, p.Name };
        return mybranchList.ToArray();
    }

客户方保留价值: [{"Code":000,"Name":"Milan"}, {"Code":001,"Name":"Istanbul"}, {"Code":002,"Name":"Baku"},]

但我想这样:

[{000:"Milan"},{001:"Istanbul"},{002:"Baku"}]

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

首先要做的事情:

[{000:"Milan"},{001:"Istanbul"},{002:"Baku"}]

是无效的JSON。属性必须如此引用:

[{"000":"Milan"},{"001":"Istanbul"},{"002":"Baku"}]

为了实现此输出,您可以使用Dictionary<string, string> JavaScriptSerializer将序列化为所需的输出。因此,只需在模型上调用ToDictionary扩展方法,以便将其转换为字典:

就像那样:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getBranchViaJson()
{
    var branches = 
        from p in getBranchs(AppSession.BranchID.Value)
        select new { p.Code, p.Name };
    var model = branches.ToDictionary(x => x.Code, x => x.Name);
    return Json(new[] { model }, JsonRequestBehavior.AllowGet);
}

或者如果你想保留你的私有方法返回一个对象,你可以让它返回一个字典:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getBranchViaJson()
{
    return Json(getBranchList(AppSession.BranchID.Value), JsonRequestBehavior.AllowGet);
}

private object getBranchList(int n)
{
    var mybranchList = from p in getBranchs(n)
             select new { p.Code, p.Name };
    return new[] { mybranchList.ToDictionary(x => x.Code, x => x.Name) };
}

请注意,我使用了new[] { model }。那是因为否则JavaScriptSerializer不会根据需要生成一个javascript数组,而是一个简单的javascript对象。

备注:请注意我已添加JsonRequestBehavior.AllowGet,以便可以使用GET请求使用此控制器操作,该请求在返回JSON响应的操作中默认禁用。

相关问题