开发者

Changing Json output ASP.net MVC

I have a ASP.net MVC application that gets marker coordinates from a database (I use ActiveRecord) and outputs them as json to be used in google maps. The format however is not quite right. Does anyone know how I can change the output?

Currently the output is:

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

It should be:

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

The code the controller:

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

And how I communicate with t开发者_Go百科he 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; }
        }


This should do the job:

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

Before returning the locations, you assign it to the Locations property of an anonymous type. This will cause JsonResult to format the output the way you want it to achieve.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜