2017-05-31 300 views
0

我有一个令人兴奋的GeoJSON文件,像这样;将属性添加到GeoJSON

{ 
    "type": "FeatureCollection", 
    "crs": { 
    "type": "name", 
    "properties": { 
     "name": "urn:ogc:def:crs:OGC:1.3:CRS84" 
    } 
    }, 
    "features": [ 
    { 
     "type": "Feature", 
     "properties": { 
     "Item": "Value" 
     }, 
     "geometry": { 
     "type": "Polygon", 
     "coordinates": [ 
      [ 
      [ 
       9.449194065548566, 
       55.86046393906458, 
       -999 
      ], 
      [ 
       9.460203211292942, 
       55.8619238071893, 
       -999 
      ], 
      [ 
       9.440463307997378, 
       55.876740797773365, 
       -999 
      ] 
      ] 
     ] 
     } 
    }, 
    { 
     "type": "Feature", 
     "properties": { 
     "Item": "Value" 
     }, 
     "geometry": { 
     "type": "Polygon", 
     "coordinates": [ 
      [ 
      [ 
       8.59655725301728, 
       55.53506085541584, 
       -999 
      ], 
      [ 
       8.601439658322603, 
       55.52856219238175, 
       -999 
      ] 
      ] 
     ] 
     } 
    } 
    ] 
} 

我需要加载该文件,将属性添加到每个特征,并将其保存为一个新的JSON文件。 什么是在C#中最好的方法呢?

我可以像这样加载文件;

using (StreamReader r = new StreamReader(Server.MapPath("~/test.json"))) 
     { 
      string json = r.ReadToEnd(); 
      List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json); 
     } 

但是,那又如何?

+1

反序列化JSON到型号附加属性,设置属性,序列化到文件。 – Reniuz

+0

正如@brother指出的,你必须在反序列化之前添加属性来设置属性,然后再次将其序列化。 –

+0

我知道背后的理论,即我需要添加属性,但我该怎么做 - 你有一个例子吗? – brother

回答

0

您可以使用GDAL/OGR的OGR库部分读取geojson文件。 OGR能够直接读取GeoJSON格式导出: http://gdal.org/1.11/ogr/drv_geojson.html

不幸为C#GDAL/OGR绑定的文档是相当差。

但是你可以对如何使用OGR访问GeoJSON的功能在此示例中看看:

https://trac.osgeo.org/gdal/browser/trunk/gdal/swig/csharp/apps/OGRFeatureEdit.cs

所以,你可以使用:

Ogr.RegisterAll(); // To register the OGR drivers especially geojson 
DataSource ds = Ogr.Open(<path to your geojson>, 1); 
Layer layer = ds.GetLayerByName("the name of the layer"); 

// Finally iterate over all features you want to modify 
Feature feature = layer.GetFeature(0); 
feature.SetField(<set your fields>); 

// write your feature back to your layer 
layer.SetFeature(feature) 
+0

我可以使用Newtonsoft.Json和/或GeoJSON.Net对于任务,而不是? – brother

+0

你也可以用另一个JSON解析器/读写器来完成它,但由于它是某种地理数据,我会用GDAL/OGR来完成。特别是如果您可能希望稍后更改地理数据的投影或类似的内容;你不会绕过它;-) –

+0

我不想改变地理数据 - 我只想添加一个属性到每个功能,然后再次保存,作为一个确切的副本,新属性添加到每个功能 – brother