3

尝试反序列化从 Web 源返回的以下 json:

{
    "cards": [
    {
        "high": "8.27", 
        "volume": 5, 
        "percent_change": "0.00", 
        "name": "Wurmcoil engine", 
        "url": "http://blacklotusproject.com/cards/Scars+of+Mirrodin/Wurmcoil+Engine/", 
        "price": "6.81", 
        "set_code": "SOM", 
        "average": "5.67", 
        "change": "0.00", 
        "low": "1.12"}], 
        "currency": "USD"
    }

我正在使用带有visual basic的json.net,这对他们来说都是新的,尤其是vb的面向对象部分。我只想提取“价格”变量。我已经建立了一个这样的类:

Public Class Card
    Public high As String
    Public volume As String
    Public percent_change As String
    Public name As String
    Public url As String
    Public price As String
    Public set_code As String
    Public average As String
    Public change As String
    Public low As String
End Class

我目前使用的代码是:

Public Sub parse_json(url As String)
    Dim blp_json As String = ""
    Dim wClient As New WebClient
    wClient.Proxy = System.Net.HttpWebRequest.DefaultWebProxy
    blp_json = wClient.DownloadString(url)
    MessageBox.Show(blp_json)
    Dim card_1 = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Card)(blp_json)
    PriceTextBox.Text = card_1.price
    TextBox1.AppendText(card_1.ToString)
    TextBox1.AppendText(blp_json)

End Sub

只是尝试了许多不同的事情来掌握它,不确定我在做什么。我认为我的卡片类不正确,因为“价格”似乎嵌套在卡片中:[{...}]

我根本不知道反序列化 json,更不用说如何在 vb 中 /properly/ 进行反序列化了。

4

1 回答 1

0

我使用System.Web.Script.Serialization.JavaScriptSerializerJSON 反序列化。cards由于包含 JSON 对象数组,您的示例稍微复杂了一点。这由“[”和“]”表示。此示例代码将向您展示如何处理它,无论是否cards为数组。Else如果您确定总会有一个数组,您可能希望忽略cards

确保在项目中包含对 System.Web.Extensions 的引用,并且...

Imports System.Web.Script.Serialization

进而...

Dim MySerializer As JavaScriptSerializer = New JavaScriptSerializer()
Dim dictResult As Dictionary(Of String, Object) = MySerializer.Deserialize(Of Dictionary(Of String, Object))(blp_json)

Dim dictCard As Dictionary(Of String, Object)

If dictResult.ContainsKey("cards") Then

    If TypeOf dictResult("cards") Is ArrayList Then

        Dim arrResult As ArrayList = DirectCast(dictResult("cards"), ArrayList)

        For Each arrCardRecord In arrResult

            dictCard = DirectCast(arrCardRecord, Dictionary(Of String, Object))

            If dictCard.ContainsKey("price") Then Console.WriteLine(dictCard("price"))

        Next
    Else
        dictCard = DirectCast(dictResult("cards"), Dictionary(Of String, Object))
        If dictCard.ContainsKey("price") Then Console.WriteLine(dictCard("price"))
    End If

End If
于 2013-02-11T13:44:58.800 回答