我试图将json转换为数据库的平面文件。 为了做到这一点,我必须在根节点中获取一些值,然后在特定子节点中获取一个键,然后每个键的子节点值。
for each
,JObject
和JToken
JProperty
和投射问题是一场噩梦
源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
...
我失败的例子受到围绕SO的C#答案的启发,但价值的关键是&#34;值。似乎很少见。
答案 0 :(得分:1)
您可以将它们作为对象的集合并迭代:
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
键:13,纬度:46.08562,长:3.460492
key:1bis,lat:46.08686,long:3.459992
key:5,lat:46.08647,long:3.460912
030010014B
将出现在您的Id变量中