我正在尝试从我的数据库中检索一些数据以在GoogleMaps API中使用,但我不确定如何将其格式化为GeoJson。
目前,我的代码如下:
public IActionResult GetAll()
{
using (var connection = new SqlConnection(_config.GetConnectionString("MainDatabase")))
{
var results = connection.Query(
@"SELECT [Car] = car_no,
[Latitude] = lat,
[Longitude] = lng,
[Status] = status
FROM dbo.vehicles vh"
);
return Json(results);
}
}
但是这会以“普通”json格式返回它,我需要将其格式化为以类似于此的格式返回:
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [102.0, 0.5]
},
"properties": {
"car": "15",
"status": "arrived"
}
}]
}
答案 0 :(得分:1)
您可以使用json.net根据您的查询结果创建自定义JSON字符串(因为我不知道格式Query
返回代码示例中我假设属性的数据)
var features = new JArray();
foreach (var result in results)
{
features.Add(new JObject(
new JProperty("type", "Feature"),
new JProperty("geometry", new JObject(
new JProperty("type", "Point"),
new JProperty("coordinates", new JArray(
new JValue(result.Latitude),
new JValue(result.Longitude)
))
)),
new JProperty("properties", new JObject(
new JProperty("car", result.Car),
new JProperty("status", "arrived")
))
));
}
var jsonObject = new JObject
{
new JProperty("type", "FeatureCollection"),
new JProperty("features", features)
};
var json = jsonObject.ToString();