将属性添加到GeoJSON
问题描述:
我有一个令人兴奋的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);
}
但是,那又如何?
答
您可以使用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)
反序列化JSON到型号附加属性,设置属性,序列化到文件。 – Reniuz
正如@brother指出的,你必须在反序列化之前添加属性来设置属性,然后再次将其序列化。 –
我知道背后的理论,即我需要添加属性,但我该怎么做 - 你有一个例子吗? – brother