改变Json输出ASP.net MVC

时间:2010-09-15 15:09:10

标签: json asp.net-mvc-2 active-directory format

我有一个ASP.net MVC应用程序,它从数据库中获取标记坐标(我使用ActiveRecord)并将它们输出为json以在谷歌地图中使用。但格式并不完全正确。有谁知道我怎么能改变输出?

目前的输出是:

 [
    {
        "Id": 1,
        "Name": null,
        "Location": "13.79194402, 100.71588015" 
    },
    {
        "Id": 2,
        "Name": null,
        "Location": "13.79194402, 100.71588015",
...

应该是:

{
"locations": [
    {
        "Id": 1,
        "Name": null,
        "Location": "13.79194402, 100.71588015" 
    },
    {
        "Id": 2,
        "Name": null,
        "Location": "13.79194402, 100.71588015",
...

控制器的代码:

public ActionResult Map()
    {
        var map = DeviceLocation.FindAll();
        return Json(map, JsonRequestBehavior.AllowGet);
    }

以及我如何与db通信:

[ActiveRecord("Location")]
    public class DeviceLocation : ActiveRecordValidationBase<DeviceLocation> 
    {
        private int _id;
        private string _name;
        private string _location;

        [PrimaryKey("Id")]
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        [Property("Name")]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        [Property("Coords")]
        public string Location
        {
            get { return _location; }
            set { _location = value; }
        }

1 个答案:

答案 0 :(得分:1)

这应该做的工作:

public ActionResult Map()
{
    var map = DeviceLocation.FindAll();
    var locations = new { Locations = map };
    return Json(locations, JsonRequestBehavior.AllowGet);
}

在返回位置之前,将其分配给匿名类型的Locations属性。这将导致JsonResult以您希望的方式格式化输出。