如何使用VB.NET反序列化此JSON [英] How to deserialize this JSON with VB.NET

查看:74
本文介绍了如何使用VB.NET反序列化此JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON数据:

I have this JSON data:

{询问":[["0.26039995",19.91610429],["0.26063345",3070.562292]],出价":[["0.26000017",30381.45513902],["0.26000000",8299.1410574]],"isFrozen :" 0," seq:50663190}

{"asks":[["0.26039995",19.91610429],["0.26063345",3070.562292]],"bids":[["0.26000017",30381.45513902],["0.26000000",8299.1410574]],"isFrozen":"0","seq":50663190}

我写了这段代码:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim wc As New WebClient
    Dim sURL As String = "https://poloniex.com/public?command=returnOrderBook&currencyPair=USDT_STR&depth=" & 2
    Dim res As String = wc.DownloadString(New Uri(sURL))

    Dim m As IEnumerable(Of Rootobject) = JsonConvert.DeserializeObject(Of IEnumerable(Of Rootobject))(res)
End Sub


Public Class Rootobject
    Public Property asks As asksDef()
    Public Property bids As bidsDef()
    Public Property isFrozen As String
    Public Property seq As Integer
End Class

Public Class asksDef
    Public Property priceAsk As String
    Public Property quantAsk As Integer
End Class

Public Class bidsDef
    Public Property priceBid As String
    Public Property quantBid As Integer
End Class

我用VB paste special粘贴了JSON类. 问题是:如何访问每个ask,每个bid以及isFrozenseq值.

I've pasted the JSON class with VB paste special. The question is: how to access to every ask, every bid and the isFrozen and seq values.

我在此行出现错误:

Dim m As IEnumerable(Of Rootobject) = JsonConvert.DeserializeObject(Of IEnumerable(Of Rootobject))(res)

我收到的错误消息是:

类型的未处理异常 "Newtonsoft.Json.JsonSerializationException"发生在 Newtonsoft.Json.dll

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

其他信息:无法反序列化当前JSON对象 (例如{"name":"value"}) 'System.Collections.Generic.IEnumerable`1 [poloniexAPI.Rootobject]' 因为该类型需要JSON数组(例如[1,2,3])进行反序列化 正确.

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

要解决此错误,请将JSON更改为JSON数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的.NET 类型(例如,不是整数之类的原始类型,不是集合类型 (例如数组或列表),可以从JSON对象反序列化. 也可以将JsonObjectAttribute添加到类型中以强制将其 从JSON对象反序列化.

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) 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.

路径询问",第1行,位置8.

Path 'asks', line 1, position 8.

这次我再次被这个JSON模型所困扰.如何进行呢?

I'm stuck again this time with this JSON model. How to proceed with this?

{"BTC_BCN":{"id":7,"last":"0.00000042","lowestAsk":"0.00000043","highestBid":"0.00000042","percentChange":"0.00000000","baseVolume" :"179.56364789","quoteVolume":"436786711.33832335","isFrozen":"0","high24hr":"0.00000043","low24hr":"0.00000039"},"BTC_BELA":{"id":8,"last:" 0.00002091," lowestAsk:" 0.00002097," highestBid:" 0.00002091," percentChange:"-0.10831556," baseVolume:" 12.57891843," quoteVolume:" 579476.06165462," isFrozen :" 0," high24hr:" 0.00002345," low24hr:" 0.00002088}}

{"BTC_BCN":{"id":7,"last":"0.00000042","lowestAsk":"0.00000043","highestBid":"0.00000042","percentChange":"0.00000000","baseVolume":"179.56364789","quoteVolume":"436786711.33832335","isFrozen":"0","high24hr":"0.00000043","low24hr":"0.00000039"},"BTC_BELA":{"id":8,"last":"0.00002091","lowestAsk":"0.00002097","highestBid":"0.00002091","percentChange":"-0.10831556","baseVolume":"12.57891843","quoteVolume":"579476.06165462","isFrozen":"0","high24hr":"0.00002345","low24hr":"0.00002088"}}

推荐答案

此特定错误的根本原因是您的JSON表示单个对象(其中包含一些数组和其他信息),但是您试图像对它进行反序列化一样整个事情都是无法计数的.但是,解决此问题不能解决整个问题.还有其他两个问题.

The root cause of this specific error is that your JSON represents a single object (which contains some arrays and other info) but you are trying to deserialize it as if the whole thing were enumerable. However, fixing this will not solve the whole problem; there are a couple of other issues as well.

此JSON有点奇怪,因为它使用数组将出价和要价的每个价格和数量对组合在一起,而对象似乎更合适(并且更容易消耗).由于Json.Net没有通过索引自动将数组映射到类属性的功能,因此您将需要使用自定义JsonConverter正确反序列化此数据.同样,出于某种原因,价格也用字符串表示,它们应该像数量一样为小数.这也可以在转换器中处理.

This JSON is a little odd because it uses an array to group together each price and quantity pair for the bids and asks, whereas an object seems like it would be more appropriate (and more easily consumable). Since Json.Net does not have a facility to automatically map an array into class properties by index, you will need to use a custom JsonConverter to deserialize this data properly. Also, the prices are represented as strings for some reason where they should be decimals like the quantity. This can be handled in the converter as well.

在进入转换器之前,让我们修复您的类定义.由于出价和要价使用相同的结构,因此我建议为此定义一个通用类. pricequantity属性都应声明为Decimal:

Before we get to the converter, let's fix your class definitions. Since the bids and asks use the same structure, I would recommend defining a common class for that. Both price and quantity properties should be declared as Decimal:

Public Class PriceQuantityPair
    Public Property price As Decimal
    Public Property quantity As Decimal
End Class

然后像这样定义您的根类:

Then define your root class like this:

Class RootObject
    Public Property asks As List(Of PriceQuantityPair)
    Public Property bids As List(Of PriceQuantityPair)
    Public Property isFrozen As String
    Public Property seq As Integer
End Class

这是转换器的代码,它将把每一对的数组结构转换为一个PriceQuantityPair实例:

Here is the code for the converter, which will translate the array structure for each pair into a PriceQuantityPair instance:

Class PriceQuantityPairConverter
    Inherits JsonConverter

    Public Overrides Function CanConvert(objectType As Type) As Boolean
        Return objectType Is GetType(PriceQuantityPair)
    End Function

    Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
        Dim ja As JArray = JArray.Load(reader)
        Dim pair As PriceQuantityPair = New PriceQuantityPair()
        pair.price = ja(0).ToObject(Of Decimal)()
        pair.quantity = ja(1).ToObject(Of Decimal)()
        Return pair
    End Function

    Public Overrides ReadOnly Property CanWrite As Boolean
        Get
            Return False
        End Get
    End Property

    Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
        Throw New NotImplementedException()
    End Sub
End Class

要使用转换器,请在PriceQuantityPair类中添加一个<JsonConverter>属性,如下所示:

To use the converter, add a <JsonConverter> attribute to the PriceQuantityPair class like this:

<JsonConverter(GetType(PriceQuantityPairConverter))>
Public Class PriceQuantityPair
    ...
End Class

最后,像这样将JSON反序列化为RootObject类:

Finally, deserialize the JSON into the RootObject class like this:

Dim root As RootObject = JsonConvert.DeserializeObject(Of RootObject)(json)

这是一个演示: https://dotnetfiddle.net/dDHLtR

这篇关于如何使用VB.NET反序列化此JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆