开发者

Changing Json output ASP.net MVC

开发者 https://www.devze.com 2023-01-16 11:44 出处:网络
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 anyon

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

精彩评论

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

关注公众号