我試圖在Visual Basic中使用JSON.NET庫將一個簡單的JSON數組反序列化爲.NET對象。反序列化VB.NET中的JSON數據的問題
對於我的生活,我無法弄清楚我在這裏做錯了什麼。我的JSON字符串反序列化成適當的對象(總共9個),但沒有填充任何屬性。
我的代碼:
Public Class result
Public Property id As Integer
Public Property vote_percentage As String
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal vote_percentage As String)
Me.id = id
Me.vote_percentage = vote_percentage
End Sub
End Class
的JSON數據,我嘗試反序列化看起來像這樣:
[{ 「入圍」:{ 「ID」:12, 「vote_percentage」:」 28 「}},{」 決賽 「:{」 ID 「:13,」 vote_percentage 「:」 6 「}},{」 決賽 「:{」 ID 「:14,」 vote_percentage 「:」 4" }},{ 「決賽」:{ 「ID」:15, 「vote_percentage」: 「3」}},{ 「決賽」:{ 「ID」:16, 「vote_percentage」: 「7」}},{ 「決賽」:{」 ID 「:17,」 vote_percentage 「:」 1 「}},{」 決賽 「:{」 ID 「:18,」 vote_percentage 「:」 47 「}},{」 決賽 「:{」 ID 「:19,」 vote_percentage「:」2「}},{」finalist「:{」id「:20,」vote_percentage「:」1「}}]
最後我反序列化:
Dim Results As New List(Of result)
Results = JsonConvert.DeserializeObject(Of List(Of result))(_result)
結果是沒有分配任何屬性值9級的對象。
我在絞盡腦汁,所以如果有人能把我的骨頭扔掉,我會很感激。
謝謝。
UPDATE:
因此,這裏是得到這個工作,我所做的更改:
- 修改了我的結果類包含類型爲入圍的屬性決賽
創建一個新的類入圍與屬性id和vote_percentage
Public Class finalist Public Property id As Integer Public Property vote_percentage As String Public Sub New() End Sub Public Sub New(ByVal id As Integer, ByVal vote_percentage As String) Me.id = id Me.vote_percentage = vote_percentage End Sub End Class Public Class result Public Property finalist As finalist Public Sub New() finalist = New finalist End Sub Public Sub New(ByVal id As Integer, ByVal vote_percentage As String) Me.finalist = New finalist(id, vote_percentage) End Sub End Class
單獨留下解串:
_result = System.Text.Encoding.ASCII.GetString(data)
Dim Results As New List(Of result)
Results = JsonConvert.DeserializeObject(Of List(Of result))(_result)
RaiseEvent VoteCompleted(loopCounter, _VoteCount, time, _result)
它工作。
爲新人(像我自己)的說明。在使用JSON.NET時,必須具有構造函數方法(即Sub New),才能在反序列化調用期間設置屬性。
你可以嘗試解析沒有包裝finalist屬性的json嗎?目前,你只有一個只有finalist屬性的對象數組,而你的類沒有這個屬性。 – pimvdb 2012-02-03 17:56:52
我不明白你的意思。你是否建議我從json字符串中移除決賽選手的所有實例?我的印象是入圍者映射到了一個結果類的單個實例。 – jdbenn 2012-02-03 18:11:38
pimvdb - 你把我帶到了一些東西上,並修復了它。我更新了我的代碼以顯示工作解決方案。 – jdbenn 2012-02-03 18:16:17