2013-09-29 46 views
0

我已經有一個問題很多麻煩了幾天,現在我對此感到非常沮喪! 我想知道如何解碼VB.NET 4.5框架中的JSON數組。我試圖使用反序列化/序列化類。 這裏是數組:解碼複雜的JSON數組vb.net

{ 「LaunchIDs」:[ 「2」, 「3」, 「4」, 「5」, 「6」, 「7」, 「8」, 「9」, 「10」], 「FavoriteID」:NULL, 「用戶名」: 「測試」, 「錯誤」:0, 「消息」: 「您已經成功登錄」}

用於陣列中的代碼是

Public Class JSONCode 
    Public LaunchIDs As Integer 
    Public FavoriteIDAs Integer 
    Public username As String 
    Public [error] As Integer 
    Public message As Integer 
End Class 

這是我在應用程序內部如何使用它。

Dim client As New WebClient() 
Dim jsonResponse As String = "{""LaunchIDs"":[""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10""],""FavoriteID"":null,""username"":""Test"",""error"":0,""message"":""You have successfully logged in""}") 
Dim serializer As New JavaScriptSerializer() 
Dim response As JSONCode = serializer.Deserialize(Of JSONCode)(jsonResponse) 
     code = response.error 
     If code = 0 & response.message = "You have successfully logged in" Then 
      LoginFunction = True 
      botids = response.botids 
      ListBox1.AddItem(botids) 
     Else 
      Alert(Style.Critical, response.message) 
     End If 
End If 

該數組將從Web地址檢索(我解決了這個問題後),所以它現在有點亂。 Alert()只是一個小小的自定義msgBox函數。

當我嘗試和調試時出現此錯誤。 類型'System.Int32'不支持數組的反序列化。

回答

0

您的類的聲明是錯誤的,應該是

Public Class JSONCode_cor 
    Public LaunchIDs As Integer() 
    Public FavoriteID As Integer() 
    Public username As String 
    Public [error] As Integer 
    Public message As String 
End Class 

這我在代碼中使用:

Dim jsonResponse As String = "{""LaunchIDs"":[""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10""],""FavoriteID"":null,""username"":""Test"",""error"":0,""message"":""You have successfully logged in""}" 
Dim serializer As New Web.Script.Serialization.JavaScriptSerializer() 
Dim response As Object = serializer.Deserialize(Of JSONCode_cor)(jsonResponse) 

和它的作品。你的問題是你聲明LaunchID爲Integer,但實際上它是一個數組Integer()

+0

frmMain.FlatListBox2.AddItem(LaunchIDs)給出了「int32」或其他值,所以我試着用AddRange切換AddItem。現在我得到 錯誤1由於'整數'不是參考類型,因此'1維數組整數'類型的值無法轉換爲'1維數組對象'。 – user2827489

+0

@ user2827489查看更新後的答案。 – IvanH

+0

這就是我已經使用的代碼。那麼我想出了這個問題,必須做一個函數來將整數轉換爲一個字符串數組。 – user2827489