尝试反序列化从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中正确地进行反序列化了。
答案 0 :(得分:0)
我使用System.Web.Script.Serialization.JavaScriptSerializer
进行JSON反序列化。由于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