2010-09-15 74 views
1

我有一個ASP.net MVC應用程序,它從數據庫中獲取標記座標(我使用ActiveRecord)並將它們輸出爲json以用於谷歌地圖。但是格式不太正確。有誰知道我可以如何改變輸出?更改Json輸出ASP.net MVC

目前的輸出是:

[ 
    { 
     "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); 
    } 

我如何與數據庫通信:

[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

這應該做的工作:

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

返回的位置之前,將其分配給一個匿名類型的位置特性。這將導致JsonResult按照您希望的方式格式化輸出。

+0

謝謝它做到了:) – Prd 2010-09-16 12:24:46