我正在尝试将json转换为数据库的平面文件。为了做到这一点,我必须在根节点中拾取一些值,然后在特定的子节点中拾取一个键,然后拾取每个键的子值。
JObject
、JToken
和JProperty
之间的for each
和cast问题是一场噩梦
源JSON
{
"id": "030010014B",
"type": "street",
"housenumbers": {
"13": {
"lat": 46.085617,
"lon": 3.460492
},
"1bis": {
"lat": 46.08686,
"lon": 3.459992
},
"5": {
"lat": 46.086469,
"lon": 3.460912
}
}
}
预期结果
// <id value>;<key of housenumber #>;<lon value>;<lat value>
030010014B;13;3.460492;46.085617
030010014B;1bis;3.459992;46.08686
030010014B;5;3.460912;46.086469
当前严重失败的代码
Dim tmpJson As JObject = JObject.Parse(<json sample as string>)
Dim house As JToken
Dim house_p As JToken
If tmpJson.Property("housenumbers") IsNot Nothing Then
For Each houses As JObject In tmpJson.Property("housenumbers").Children 'only one
For Each house In houses.Descendants
fs.Append(tmpJson.Property("id").Value.ToString & ";")
Dim hh As JProperty = house 'failing here
fs.Append(hh.Name & ";") 'no way to get a key without jproperty
For Each house_p In house.Children()
fs.AppendLine(house_p.Value(Of String)("lon") & ";" & house_p.Value(Of String)("lat"))
Next
Next
Next
End If
...
我的失败例子的灵感来自c#周围的答案SO,但"值到键到值"似乎相当罕见。
您可以将它们作为对象集合并迭代:
Public Class Location
<JsonProperty("lat")>
Public Property Latitude As Single
<JsonProperty("lon")>
Public Property Longitude As Single
End Class
然后将内部部分反序列化为sa Dictionary:
Dim jstr = from whereever
Dim jobj = JObject.Parse(jstr)
Dim id As String = jobj("id").ToString
Dim numbers = JsonConvert.DeserializeObject(Of Dictionary(Of String, Location))(jobj("housenumbers").ToString())
For Each kvp In numbers
Console.WriteLine("key:{0}, lat: {1}, long: {2}",
kvp.Key, kvp.Value.Latitude,
kvp.Value.Longitude)
Next
key:13, lat: 46.08562, long: 3.460492
关键字:1bis,后期:46.08686,长:3.459992
关键字:5、后期:46.08647、长:3.460912
030010014B
应该在Id变量