2016-09-26 224 views
1

我試圖將json轉換爲數據庫的平面文件。 爲了做到這一點,我必須在根節點中選取一些值,然後在特定的子項中鍵入一個值,然後每個鍵的子元素值。如何使用JSON.net獲取密鑰和密鑰的子值?

它原來是用JObjectJTokenJProperty

源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 

當前的代碼之間的for each和鑄的問題一個夢魘失敗失敗

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#答案的啓發,但「對值的鍵的值」似乎相當罕見。

回答

1

你可以讓他們爲對象的集合並重復說:

Public Class Location 
    <JsonProperty("lat")> 
    Public Property Latitude As Single 
    <JsonProperty("lon")> 
    Public Property Longitude As Single 
End Class 

然後反序列化內部到SA詞典:

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.0​​8562,長:3.460492
鍵:1bis,lat:46.0​​8686,長:3.459992
鍵:5,lat:46.0​​8647,長:3.460912

030010014B將是你的ID變量

+0

我真的不明白髮生了什麼,但它的工程!如果我想在使用之前聲明它,那麼「數字」的類型是什麼? '數字作爲字典(字符串,位置)'不起作用 –

+0

您可以在其他地方聲明它爲字典,但是您仍然需要'DeserializeObject'方法中的'Dictionary(Of String,Location)',它告訴Json.NET什麼形式來反序列化它。 – Plutonix