2017-04-11 379 views
0

我有一個JSON返回,看起來像這樣:JSON數組的VB.NET JSON陣列 - 反序列化

{"coin1":{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"}, 
"coin2":{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"}, 
"coin3":{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"} 
} 

我想它返回到「coinName」的列表。

我做:

Public Class coinName 
    Public Vals As cValues 
End Class 

Public Class cValues 
    Public available As String 
    Public onOrders As String 
    Public btcValue As String 
End Class 

,我使用下面的代碼進行反序列化:

Dim pData = JsonConvert.DeserializeObject(Of List(Of coinName))(bals) 

「BALS」 是一個字符串形式的JSON回報。

我收到以下錯誤:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll 

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsApplication21.coinName]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 

Path '1CR', line 1, position 7. 

任何幫助將不勝感激。

謝謝。

+0

我認爲你的JSON結構不正確。 JSON數組應該如下:''汽車':[「福特」,「寶馬」,「菲亞特」]'你不應該使用** {} ** – Mederic

+0

因此,回到結構,我認爲你仍然缺少** [] **基本上你應該有:''coin3「:[{」available「:」0.00000000「,」onOrders「:」0.00000000「,」btcValue「:」0.00000000「}]'嘗試運行你的代碼更正的JSON看它是否工作。 – Mederic

+0

{「coin1」:[{「available」:「0.00000000」,「onOrders」:「0.00000000」,「btcValue」:「0.00000000」}],「coin2」:[{「available」:「0.00000000」,「onOrders 「:」0.00000000「,」btcValue「:」0.00000000「}],」coin3「:[{」available「:」0.00000000「,」onOrders「:」0.00000000「,」btcValue「:」0.00000000「}]} 不起作用 –

回答

0

我不知道他是否會幫助你我沒有太多關於VB.NET的JSON知識,但我設法得到硬幣的第一次出現。要記住你的類的東西需要具有相同的名稱作爲JSON:

Dim final As String = "" 
Dim json As String = TextBox1.Text 
Dim coincollection = JsonConvert.DeserializeObject(Of coinCollection)(json) ' Deserialize array of Post objects 
Dim coins = coincollection.coin 
If coins.Length = 1 Then ' or whatever condition you prefer 
    final = coins(0).available 
End If 

我的JSON輸入:

{"coin":[{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"}], 
"coin":[{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"}], 
"coin":[{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"}] 
} 

而且我用了兩個類是:

Public Class coinCollection 
    Public coin() As coinName 
End Class 
Public Class coinName 
    Public available As String 
    Public onOrders As String 
    Public btcValue As String 
End Class 

陣列名稱需要與JSON中的相同:硬幣

然而,包裝只獲得第一個硬幣對象,也許你可以嘗試圖解如何讀取它的所有內容。