2017-06-13 311 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();