JSON数组的VB.NET JSON数组 - 反序列化

时间:2017-04-11 08:39:35

标签: arrays 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.

非常感谢任何帮助。

谢谢。

2 个答案:

答案 0 :(得分: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中的相同:硬币

然而,包装器只获得第一个硬币对象,也许您可​​以尝试如何阅读所有这些。

答案 1 :(得分:0)

您的根JSON容器不是一个数组 - 它是一个对象,其"coinN"形式的变量属性名称适用于各种N。您可以使用变量属性名称将此类对象反序列化为字典:

Dim pData = JsonConvert.DeserializeObject(Of Dictionary(Of String, cValues))(bals)

有关文档,请参阅Serialization Guide : Dictionaries and HashtablesDeserialize a Dictionary

示例fiddle