2017-06-13 100 views
0

我试图从我的数据库中检索一些数据以用于GoogleMaps API,但我不确定如何将其格式化为GeoJson。将JSON格式化为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" 
     } 
    }] 
} 

回答

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();