Simple JSON deserialization for dummies
Attempting to deserialize the following json is returned from the web source:
{
"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"
}
I am using json.net with a visual base new to both of them, especially the object oriented vb parts. I just would like to get the "price" variable. I created the class as such:
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
The code I use is:
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
Just try different things to see what I am doing. I am assuming my card class is incorrect, as the "price" seems to be nested in the cards: [{...}]
I don't know about json deserialization at all and how to do it / correctly / in vb.
I am using System.Web.Script.Serialization.JavaScriptSerializer
JSON to deserialize. Your example gets a little more complicated because it cards
contains an array of JSON objects. This is denoted by "[" and "]". This example code will show you how to handle it whether it is an cards
array or not. You can ignore Else
if you are sure there will always be an array incards
Make sure you reference System.Web.Extensions in your project and ...
Imports System.Web.Script.Serialization
and then...
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