更改 Json 输出 ASP.net MVC
我有一个 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);
}
以及我如何与数据库通信:
[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; }
}
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 the 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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以完成工作:
在返回位置之前,将其分配给匿名类型的 Locations 属性。这将导致 JsonResult 按照您希望的方式格式化输出。
This should do the job:
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.