2014-02-10 87 views
15

我從提供程序中得到了以下簡化的JSON字符串,因爲我使用Visual Studio和vb.Net的時間很長,所以我非常生疏!簡單工作VB.net中的json.net示例

{ 
"Venue": { 
    "ID": 3145, 
    "Name": "Big Venue, Clapton", 
    "NameWithTown": "Big Venue, Clapton, London", 
    "NameWithDestination": "Big Venue, Clapton, London", 
    "ListingType": "A", 
    "Address": { 
     "Address1": "Clapton Raod", 
     "Address2": "", 
     "Town": "Clapton", 
     "County": "Greater London", 
     "Postcode": "PO1 1ST", 
     "Country": "United Kingdom", 
     "Region": "Europe" 
    }, 
    "ResponseStatus": { 
     "ErrorCode": "200", 
     "Message": "OK" 
    } 
} 
} 

我想用JSON.Net中的東西我可以工作,把這個,我讀過的例子等,並JSON.net貌似答案,但我沒有得到任何地方。

我的.Net代碼(Me.TextBox1.Text包含上面顯示的JSON)

Imports Newtonsoft.Json 

Public Class Form1 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim obj As JSON_result 
    obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TextBox1.Text) 

    MsgBox(obj.ID) 
End Sub 
End Class 

Public Class JSON_result 
    Public ID As Integer 
    Public Name As String 
    Public NameWithTown As String 
    Public NameWithDestination As String 
    Public ListingType As String 
End Class 

有人能解釋爲什麼obj.ID總是請最終爲0,爲什麼沒有其他性質的我類填充,我需要做什麼來解決這個問題,沒有錯誤報告。

回答

23

您的班級JSON_result與您的JSON字符串不匹配。請注意對象JSON_result將如何包裝在另一個名爲"Venue"的屬性中。

所以無論是創建一個類,例如:

Public Class Container 
    Public Venue As JSON_result 
End Class 

Public Class JSON_result 
    Public ID As Integer 
    Public Name As String 
    Public NameWithTown As String 
    Public NameWithDestination As String 
    Public ListingType As String 
End Class 

Dim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...) 

或更改您的JSON字符串

{ 
    "ID": 3145, 
    "Name": "Big Venue, Clapton", 
    "NameWithTown": "Big Venue, Clapton, London", 
    "NameWithDestination": "Big Venue, Clapton, London", 
    "ListingType": "A", 
    "Address": { 
     "Address1": "Clapton Raod", 
     "Address2": "", 
     "Town": "Clapton", 
     "County": "Greater London", 
     "Postcode": "PO1 1ST", 
     "Country": "United Kingdom", 
     "Region": "Europe" 
    }, 
    "ResponseStatus": { 
     "ErrorCode": "200", 
     "Message": "OK" 
    } 
} 

或使用例如一個ContractResolver來解析JSON字符串。

+7

我使用這個網站http://jsonutils.com/來自動創建JSON字符串的類來加速一些事情。以爲我會爲別人提到它。 – mikro

+0

在某些ASP.Net工具包中還有一個來自Microsoft IIRC的VS插件,但我忘了名字... – sloth

+0

@mikro,感謝您的鏈接。這將非常方便。謝謝! –

14
Imports Newtonsoft.Json.Linq 

Dim json As JObject = JObject.Parse(Me.TextBox1.Text) 
MsgBox(json.SelectToken("Venue").SelectToken("ID")) 
+0

非常感謝。 –