将 JSON 数据转换为数组/提取 .NET 中的特定节点



我有一个JSON数据,使用NewtonSoft JSON库,我无法将特定节点(坐标)提取到数组或列表中。

这是我的 JSON 数据:

{
"features":[
{
"type":"Feature",
"geometry":{
"type":"MultiPolygon",
"coordinates":[
[
[
[
28.9574884865954,
40.262043212854
],
[
28.9577391646903,
40.2620393471008
],
[
28.9581300766863,
40.2620333177299
],
[
28.9581449735233,
40.261331625691
],
[
28.9575062426388,
40.2613229341457
],
[
28.9574884865954,
40.262043212854
]
]
]
]
},
"properties":{
"ParselNo":"3",
"SayfaNo":"6966",
"Alan":"4.300,00",
"Mevkii":"",
"Nitelik":"Arsa",
"CiltNo":"70",
"Ada":"513",
"Il":"Bursa",
"Ilce":"Osmangazi",
"Pafta":"H21b25d4b",
"Mahalle":"Emek"
}
}
],
"type":"FeatureCollection",
"crs":{
"type":"name",
"properties":{
"name":"EPSG:4326"
}
}
}

我不确定我是否必须使用 JsonConvert 类或 JsonParse 类。

我"只"想将包括经度/经度值的"坐标"节点提取到定义良好的形式(如数组)或 C# 或 VB.NET 中的列表。

解析 JSON 时,您应该始终做的第一件事是转到 http://json2csharp.com 并让它为您生成类。在您的情况下,这些类是:

public class Geometry
{
public string type { get; set; }
public List<List<List<List<double>>>> coordinates { get; set; }
}
public class Properties
{
public string ParselNo { get; set; }
public string SayfaNo { get; set; }
public string Alan { get; set; }
public string Mevkii { get; set; }
public string Nitelik { get; set; }
public string CiltNo { get; set; }
public string Ada { get; set; }
public string Il { get; set; }
public string Ilce { get; set; }
public string Pafta { get; set; }
public string Mahalle { get; set; }
}
public class Feature
{
public string type { get; set; }
public Geometry geometry { get; set; }
public Properties properties { get; set; }
}
public class Properties2
{
public string name { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties2 properties { get; set; }
}
public class RootObject
{
public List<Feature> features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}

现在可以使用 JSON.NET 进行反序列化:

var root = JsonConvert.DeserializeObject<RootObject>(json);

此时,您已经获得了 RootObject 的实例。获取您想要的任何属性值。

编辑

如果你想要坐标,你必须注意的第一件事(通过研究我上面发布的类,coordinates属于Geometry类。Geometry类的实例位于Feature类中,RootObject类包含一个List<Feature>。因此,要获得coordinates,您需要遍历features并从每个coordinates中提取。

foreach(var feature in root.features)
{
var coordinatesForFeature = feature.geometry.coordinates;
}

最新更新