VB.net - JSON parse - Newtonsoft - json

I am having a troble parsing JSON using vb.net with Newtonsoft Json library.
My JSON Data is as follows :
{
"Result":"Success",
"UserID":"johns",
"Password":null,
"Locked":"False",
"Comment":"",
"LastLoggedOn":"11/9/2013 9:14:17 PM",
"NumFailedAttempts":"1",
"FirstName":"John",
"LastName":"Smith",
"MessageNum":"UA-000",
"MessageText":"Authorisation successful"
}
My code is as follows :
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(strJSONEncode)
Response.Write(a.ToString)
Response.Write(a.MessageText)
This does not produce any output.
Any help is appreciated.

Assuming your saLoginResponse class is defined like the following, and your strJSONEncode string contains the JSON data you posted in your question, your code should work fine.
Public Class saLoginResponse
Public Property Result As String
Public Property UserID As String
Public Property Password As String
Public Property Locked As Boolean
Public Property Comment As String
Public Property LastLoggedOn As String
Public Property NumFailedAttempts As String
Public Property FirstName As String
Public Property LastName As String
Public Property MessageNum As String
Public Property MessageText As String
End Class
Demo:
Sub Main()
Dim json As String = _
"{" + _
"""Result"":""Success""," + _
"""UserID"":""johns""," + _
"""Password"":null," + _
"""Locked"":""False""," + _
"""Comment"":""""," + _
"""LastLoggedOn"":""11/9/2013 9:14:17 PM""," + _
"""NumFailedAttempts"":""1""," + _
"""FirstName"":""John""," + _
"""LastName"":""Smith""," + _
"""MessageNum"":""UA-000""," + _
"""MessageText"":""Authorisation successful""" + _
"}"
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(json)
Debug.WriteLine(a.MessageText + " for " + a.FirstName + " " + a.LastName)
End Sub
Output in debug window:
Authorisation successful for John Smith

Related

Getting info from JSON in VB.NET using Json.NET

I need to process this JSON:
{
"companies": [
{
"companyId": "S86jhs89F",
"companyName": "LoremIpsum"
}
],
"response_metadata": {
"next_cursor": 659,
"next_link": "somedata"
} }
How can I get companyId, companyName, next_cursor and next_link using VB.NET?
Update...
I found this...
Dim json As String = "{ ... textJSON ... }"
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
For Each grupo As JProperty In data
grupo.CreateReader()
Select Case grupo.Name
Case "companies"
For Each item As JObject In grupo.Values
output += vbCrLf + " -- " + item("companyId").ToString
output += vbCrLf + " -- " + item("companyName").ToString
Next
Case "response_metadata"
Dim dato As JObject = grupo.Value
output += vbCrLf + " -- " + dato("next_cursor").ToString
End Select
Next
I don´t know if this is the optimal way, but it is working...
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. If you were to do this, then you would get something that looks like the following:
Public Class Rootobject
Public Property companies() As Company
Public Property response_metadata As Response_Metadata
End Class
Public Class Response_Metadata
Public Property next_cursor As Integer
Public Property next_link As String
End Class
Public Class Company
Public Property companyId As String
Public Property companyName As String
End Class
You can use decorators to make the property names conform to a more .NET style if you wanted:
Public Class Rootobject
<JsonProperty("companies")>
Public Property Companies As IEnumerable(Of Company)
<JsonProperty("response_metadata")>
Public Property ResponseMetadata As Response_Metadata
End Class
Public Class Response_Metadata
<JsonProperty("next_cursor")>
Public Property NextCursor As Integer
<JsonProperty("next_link")>
Public Property NextLink As String
End Class
Public Class Company
<JsonProperty("companyId")>
Public Property CompanyId As String
<JsonProperty("companyName")>
Public Property CompanyName As String
End Class
Now you would use JsonConvert.DeserializeObject to convert the JSON literal to your root object. After that, it's just a matter of getting the required properties:
Dim conversion = JsonConvert.DeserializeObject(Of Rootobject)(literal)
Dim companyId = conversion.Companies.First().CompanyId
Dim companyName = conversion.Companies.First().CompanyName
' etc.
Example: https://dotnetfiddle.net/GiGKwI

Get properties from Array in JSON in VB.NET

I need result from this JSON:
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjBGOTkyNkZFQTUyOTgxRjZDMjBENUMzNUQ0NjUxMzAzQ0QzQzBFMzIiLCJ0eXAiOiJhdCtqd 3QiLCJ4NXQiOiJENWttX3FVcGdmYkNEVncxMUdVVEE4MDhEakkifQ.eyJuYmYiOjE2MjA3NzEyNDEsImV4cCI6MTYyMDc3NDg0MSwiaXNzIjoiaH R0cHM6Ly9pZC5wcmVwcm9kLmV0YS5nb3YuZWciLCJhdWQiOiJJbnZvaWNpbmdBUEkiLCJjbGllbnRfaWQiOiJlZWQ4YWY2MS01ZjRmLTQxM2MtYWZlN S1jYjg0YjBiOTlhOGMiLCJJbnRlcm1lZElkIjoiMCIsIkludGVybWVkUklOIjoiIiwiSW50ZXJtZWRFbmZvcmNlZCI6IjIiLCJuYW1lIjoiMjAyNDY5NzM 1OmVlZDhhZjYxLTVmNGYtNDEzYy1hZmU1LWNiODRiMGI5OWE4YyIsInNpZCI6IjJiYzcxYTlhLWQ1MzAtMzc1ZC0zNjMzLTUwN2E3OWFjY2Y1ZiIsInByZW ZlcnJlZF91c2VybmFtZSI6IkVSUCIsIlRheElkIjoiNTE4MDEiLCJUYXhSaW4iOiIyMDI0Njk3MzUiLCJQcm9mSWQiOiI1NDgxNCIsIklzVGF4QWRtaW4iO
iIwIiwiSXNTeXN0ZW0iOiIxIiwiTmF0SWQiOiIiLCJzY29wZSI6WyJJbnZvaWNpbmdBUEkiXX0.IIxTKWdH0cUInlzrIMON95f7S6vW-CBfRoK8ZxOI6mqp
DbRLBaZQZyNoYl4A6JYQR6FJY4YVIFUsAbkKEKwwB1MaOpMMWmkyySfUmgvBMvEo6EZnT-oewnSd2EPF_bIK7-HTGug7Rjdy__wTpBr-6PH5kzR79xXzNh_s
R7TIPcvjJ-nx7eNZREdk4J7M3X8Mfjzww2RkbizN5zXNpmc5OHh_VLtlkA-4zQrs102HA9VFTxLEIdXhrpBqEBmy9dt-onZpuiKbkioV5iH2uwAkQbDvnM9h
p7EJscL0y0xFjfwbAUxQx3ohcXtA31fwyYazKQVKHCtNm9SPgSsQ-rKevQ",
"expires_in": 3600,
"scope": "Accecc DB"
}
I used:
Dim Mytoken As JObject = JObject.Parse(TextBox1.Text)
TextBox2.Text = Mytoken.SelectToken("access_token").ToString
Now I Need to get the uuid, longId, internalId, and hashKey from the acceptedDocuments like this:
{
"submissionId": "5hfhfgy5653uytyu45fg457",
"acceptedDocuments": [
{
"uuid": "hlg5fdg7ggnjgh",
"longId": "jgjhk78jm,jhk54567ujnfgh7fggh",
"internalId": "477",
"hashKey": "dfgdfhdyjfghryjghjj"
}
],
"rejectedDocuments": []
}
You could use Newtonsoft.Json and deserialize the response into an object:
Imports Newtonsoft.Json
Public Class Submission
Public submissionId As String
Public acceptedDocuments As List(Of AcceptedDocuments)
Public rejectedDocuements As String 'not sure of the type of this property
End Class
Public Class AcceptedDocuments
Public uuid As String
Public longId As String
Public internalId As Integer
Public hashKey As String
End Class
Public Function DeserilizeJson(ByRef json As String) As Submission
Dim doc As Submission = JsonConvert.DeserializeObject(Of Submission)(json)
Return doc
End Function
This should result in a Submission class object being created, to which you can reference all of the members of it, including the List of AcceptedDocuments (you can iterate over the list as needed).
I solved the problem
Dim Mytoken As JObject = JObject.Parse(TextBox1.Text)
TextBox2.Text = "My submissionId IS: " & Mytoken.SelectToken("submissionId").ToString & Environment.NewLine & Environment.NewLine
Dim arrray As JArray = JArray.Parse(Mytoken.SelectToken("acceptedDocuments").ToString)
For Each acceptedDocuments In arrray
TextBox2.Text = TextBox2.Text & "My uuid IS: " & acceptedDocuments.SelectToken("uuid").ToString & Environment.NewLine
TextBox2.Text = TextBox2.Text & "My longId IS: " & acceptedDocuments.SelectToken("longId").ToString & Environment.NewLine
TextBox2.Text = TextBox2.Text & "My internalId IS: " & acceptedDocuments.SelectToken("internalId").ToString & Environment.NewLine
TextBox2.Text = TextBox2.Text & "My hashKey IS: " & acceptedDocuments.SelectToken("hashKey").ToString & Environment.NewLine
Next

How to read and process multiple JSON API responses asynchronously?

I'm reading JSON responses from the Binance Api, from this link
I need to get some of the data out of it and this is the code I'm using:
Imports System.Net
Imports Newtonsoft.Json
Imports System.Collections.Generic
Public Class Form1
Private wc As New WebClient()
Private wc1 As New WebClient()
Private wc2 As New WebClient()
Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim btc = Await wc.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim doge = Await wc1.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=DOGEEUR")
Dim bnb = Await wc2.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(btc)
Dim d1 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(doge)
Dim d2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(bnb)
Label1.Text = "PRICE " + d("lastPrice")
Label2.Text = "24H CHANGE " + d("priceChange")
Label3.Text = "24H CHANGE % " + d("priceChangePercent")
Label4.Text = "HIGH 24H " + d("highPrice")
Label5.Text = "LOW 24H " + d("lowPrice")
Label6.Text = "PRICE " + d1("lastPrice")
Label7.Text = "24H CHANGE " + d1("priceChange")
Label8.Text = "24H CHANGE % " + d1("priceChangePercent")
Label9.Text = "HIGH 24H " + d1("highPrice")
Label10.Text = "LOW 24H " + d1("lowPrice")
Label11.Text = "PRICE " + d2("lastPrice")
Label12.Text = "24H CHANGE " + d2("priceChange")
Label13.Text = "24H CHANGE % " + d2("priceChangePercent")
Label14.Text = "HIGH 24H " + d2("highPrice")
Label15.Text = "LOW 24H " + d2("lowPrice")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Start()
End Sub
End Class
This code is working perfectly, the Timer.Intrval is set at 1000ms, but after a while I'm getting an exception:
System.NotSupportedException: WebClient does not support concurrent I/O operations
in the line:
Dim bnb = Await wc2.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
How can I solve it? It doesn't seems wrong cause I'm using 3 different WebClients objects to do that.
Also, how can I just display just 2 decimals after the comma ?
Since you have all async method to call, I suggest to move the API requests to an async method that, when initialized, keeps sending requests to the API - with a delay between calls - until the CancellationToken passed to the method signals that its time to quit.
I'm passing a Progress<T> delegate to the method, which is responsible to update the UI when the Tasks started by the aysnc method return their results.
The delegate of course executes in the UI Thread (here; anyway, the Thread that created and initialized it).
You can run this method from any other method / event handler that can be aysnc. Here, for example, the Click handler of a button. You can also start it from the Form.Load handler. Or whatever else.
I've decide to deserialize the JSON responses to a class model, since some values need to be converted to different types to make sense. As the Date/Time values returned, which are expressed in Unix (milliseconds) notation. So I'm using a custom UnixDateTimeConverter to convert the Date/Time values to DateTimeOffset structures.
Imports System.Net
Imports System.Net.Http
Imports System.Threading
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Converters
Private ctsBinance As CancellationTokenSource = Nothing
Private Async Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
ctsBinance = New CancellationTokenSource()
Dim progressReport = New Progress(Of BinanceResponseRoot())(AddressOf BinanceProgress)
Try
' Pass the Pogress<T> delegate, the delay in ms and the CancellationToken
Await DownLoadBinanceData(progressReport, 1000, ctsBinance.Token)
Catch tcEx As TaskCanceledException
Console.WriteLine("Tasks canceled")
Finally
ctsBinance.Dispose()
End Try
End Sub
Private Sub BinanceProgress(results As BinanceResponseRoot())
Console.WriteLine("PRICE " & results(0).LastPrice.ToString("N2"))
Console.WriteLine("24H CHANGE " & results(0).PriceChange.ToString("N2"))
Console.WriteLine("24H CHANGE % " & results(0).PriceChangePercent.ToString("N2"))
Console.WriteLine("HIGH 24H " & results(0).HighPrice.ToString("N2"))
Console.WriteLine("LOW 24H " & results(0).LowPrice.ToString("N2"))
Console.WriteLine("PRICE " & results(1).LastPrice.ToString("N2"))
Console.WriteLine("24H CHANGE " & results(1).PriceChange.ToString("N2"))
Console.WriteLine("24H CHANGE % " & results(1).PriceChangePercent.ToString("N2"))
Console.WriteLine("HIGH 24H " & results(1).HighPrice.ToString("N2"))
Console.WriteLine("LOW 24H " & results(1).LowPrice.ToString("N2"))
Console.WriteLine("PRICE " & results(1).LastPrice.ToString("N2"))
Console.WriteLine("24H CHANGE " & results(2).PriceChange.ToString("N2"))
Console.WriteLine("24H CHANGE % " & results(2).PriceChangePercent.ToString("N2"))
Console.WriteLine("HIGH 24H " & results(2).HighPrice.ToString("N2"))
Console.WriteLine("LOW 24H " & results(2).LowPrice.ToString("N2"))
End Sub
To cancel the execution of the Tasks, call the Cancel() method of the CancellationTokenSource. If the Tasks are not canceled before the Form / Window closes, call it when the Form / Window is closing, handling that event.
ctsBinance?.Cancel()
ctsBinance = Nothing
The worker method:
The method keeps running queries to the API in parallel until a cancellation is requested, calling the Cancel() method of the CancellationTokenSource.
I'm using a static HttpClient to send the API requests, since this is more likely its kind of job (no custom initialization, it uses all defaults: you may need to initialize a HttpClientHandler in some contexts, as specific Security Protocols).
All HttpClient.GetAsStringAsync() Tasks are added to a List(Of Task), then all Tasks are executed calling Task.WhenAll().
When all Tasks return, the API responses are deserialized to the BinanceResponseRoot model and the Progress<T> delegate is called to update the UI with the information received.
Private Shared binanceClient As New HttpClient()
Public Async Function DownLoadBinanceData(progress As IProgress(Of BinanceResponseRoot()),
delay As Integer, token As CancellationToken) As Task
While Not token.IsCancellationRequested
Dim tasks As New List(Of Task(Of String))({
binanceClient.GetStringAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR"),
binanceClient.GetStringAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=DOGEEUR"),
binanceClient.GetStringAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
})
Await Task.WhenAll(tasks)
Dim btcEur = JsonConvert.DeserializeObject(Of BinanceResponseRoot)(tasks(0).Result)
Dim dogeEur = JsonConvert.DeserializeObject(Of BinanceResponseRoot)(tasks(1).Result)
Dim bnbEur = JsonConvert.DeserializeObject(Of BinanceResponseRoot)(tasks(2).Result)
progress.Report({btcEur, dogeEur, bnbEur})
Await Task.Delay(delay, token)
End While
End Function
Class Model to convert that JSON data to the corresponding .Net Type values:
Public Class BinanceResponseRoot
Public Property Symbol As String
Public Property PriceChange As Decimal
Public Property PriceChangePercent As Decimal
Public Property WeightedAvgPrice As Decimal
Public Property PrevClosePrice As Decimal
Public Property LastPrice As Decimal
Public Property LastQty As Decimal
Public Property BidPrice As Decimal
Public Property BidQty As Decimal
Public Property AskPrice As Decimal
Public Property AskQty As Decimal
Public Property OpenPrice As Decimal
Public Property HighPrice As Decimal
Public Property LowPrice As Decimal
Public Property Volume As Decimal
Public Property QuoteVolume As Decimal
<JsonConverter(GetType(BinanceDateConverter))>
Public Property OpenTime As DateTimeOffset
<JsonConverter(GetType(BinanceDateConverter))>
Public Property CloseTime As DateTimeOffset
Public Property FirstId As Long
Public Property LastId As Long
Public Property Count As Long
End Class
Friend Class BinanceDateConverter
Inherits UnixDateTimeConverter
Public Overrides Function CanConvert(t As Type) As Boolean
Return t = GetType(Long) OrElse t = GetType(Long?)
End Function
Public Overrides Function ReadJson(reader As JsonReader, t As Type, existingValue As Object, serializer As JsonSerializer) As Object
Dim uxDT As Long? = serializer.Deserialize(Of Long?)(reader)
Return DateTimeOffset.FromUnixTimeMilliseconds(uxDT.Value)
End Function
Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
Dim dtmo = DirectCast(value, DateTimeOffset)
If dtmo <> DateTimeOffset.MinValue Then
serializer.Serialize(writer, CType(DirectCast(value, DateTimeOffset).ToUnixTimeMilliseconds(), ULong))
Else
MyBase.WriteJson(writer, Nothing, serializer)
End If
End Sub
End Class
1000ms is probably too fast, the wc2.DownloadStringTaskAsync task is probably not finished. You can Stop your timer before starting those download tasks and Start it again when the tasks are done:
Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop
Dim downloadTasks As New List(Of Task(Of String))
Dim btc = wc.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCEUR")
Dim doge = wc1.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=DOGEEUR")
Dim bnb = wc2.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BNBEUR")
downloadTasks.Add(btc)
downloadTasks.Add(doge)
downloadTasks.Add(bnb)
Await Task.WhenAll(downloadTasks)
Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(btc.Result)
Dim d1 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(doge.Result)
Dim d2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(bnb.Result)
Label1.Text = "PRICE " + d("lastPrice")
Label2.Text = "24H CHANGE " + d("priceChange")
Label3.Text = "24H CHANGE % " + d("priceChangePercent")
Label4.Text = "HIGH 24H " + d("highPrice")
Label5.Text = "LOW 24H " + d("lowPrice")
Label6.Text = "PRICE " + d1("lastPrice")
Label7.Text = "24H CHANGE " + d1("priceChange")
Label8.Text = "24H CHANGE % " + d1("priceChangePercent")
Label9.Text = "HIGH 24H " + d1("highPrice")
Label10.Text = "LOW 24H " + d1("lowPrice")
Label11.Text = "PRICE " + d2("lastPrice")
Label12.Text = "24H CHANGE " + d2("priceChange")
Label13.Text = "24H CHANGE % " + d2("priceChangePercent")
Label14.Text = "HIGH 24H " + d2("highPrice")
Label15.Text = "LOW 24H " + d2("lowPrice")
Timer1.Start
End Sub
That way you will be sure the previous download has completed.
You can also check if the WebClient is still busy using the WebClient.IsBusy property before starting another download.
As far as displaying 2 decimals, take a look at Strings.FormatNumber. You can specify a NumDigitsAfterDecimal parameter that indicates
how many places are displayed to the right of the decimal. The default value is -1, which indicates that the computer's regional settings are used.

Deserializing JSON in Visual basic

Basically, I'm trying to parse the comments from a 4chan thread using the 4chan JSON API. https://github.com/4chan/4chan-API
basically, there is one rich text box called input, and another called post_text_box. What im trying to do is make it so that JSON from a 4chan thread entered in the input text box, and comments are extracted from that JSON and displayed in the output text box
however, whenever I try clicking the Go button nothing happens.
Here is my code so far
Imports System.Web.Script.Serialization
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub start_button_Click(sender As Object, e As EventArgs) Handles start_button.Click
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Post)(input.Text)
post_text_box.Text = j.com
End Sub
End Class
Public Class Rootobject
Public Property posts() As Post
End Class
Public Class Post
Public Property no As Integer
Public Property now As String
Public Property name As String
Public Property com As String
Public Property filename As String
Public Property ext As String
Public Property w As Integer
Public Property h As Integer
Public Property tn_w As Integer
Public Property tn_h As Integer
Public Property tim As Long
Public Property time As Integer
Public Property md5 As String
Public Property fsize As Integer
Public Property resto As Integer
Public Property bumplimit As Integer
Public Property imagelimit As Integer
Public Property replies As Integer
Public Property images As Integer
End Class
Since you're importing Newtonsoft.Json, you can just use the JsonConvert.DeserializeObject<T>(String) method:
Dim exampleJson As String = "{ 'no':'123', 'name':'Some Name', 'com':'This is a comment'}"
Dim post As Post = JsonConvert.DeserializeObject(Of Post)(exampleJson)
Dim com As String = post.com
post_text_box.Text = com
Alternatively, if you don't want to create a class for Post, you can use JsonConvert.DeserializeAnonymousType<T>(String, T):
Dim exampleJson As String = "{ 'no':'123', 'name':'Some Name', 'com':'This is a comment'}"
Dim tempPost = New With {Key .com = ""}
Dim post = JsonConvert.DeserializeAnonymousType(exampleJson, tempPost)
Dim com As String = post.com
post_text_box.Text = com
EDIT: It looks like you're getting an array back from the API:
{
"posts" : [{
"no" : 38161812,
"now" : "11\/19\/13(Tue)15:18",
"name" : "Anonymous",
"com" : ‌​ "testing thread for JSON stuff",
"filename" : "a4c",
"ext" : ".png",
"w" : 386,
"h" : 378,
"tn_w" : 250,
"tn_h" : 244,
"tim" ‌​ : 1384892303386,
"time" : 1384892303,
"md5" : "tig\/aNmBqB+zOZY5upx1Fw==",
"fsize" : 6234,
"‌​resto" : 0,
"bumplimit" : 0,
"imagelimit" : 0,
"replies" : 0,
"images" : 0
}
]
}
In that case, you will need to change the type that is being deserialized to Post():
First, add another small wrapper class:
Public Class PostWrapper
Public posts() As Post
End Class
Then adjust your deserialization code:
Dim json As String = input_box.Text
Dim postWrapper = JsonConvert.DeserializeObject(Of PostWrapper)(json) ' Deserialize array of Post objects
Dim posts = postWrapper.posts
If posts.Length = 1 Then ' or whatever condition you prefer
post_text_box.Text = posts(0).com
End If
Instead of needing to define a class, you can deserialize the JSON into an Object, like this:
Dim json As String = "{""items"":[{""Name"":""John"",""Age"":""20"",""Gender"":""Male""},{""Name"":""Tom"",""Age"":""25"",""Gender"":""Male""},{""Name"":""Sally"",""Age"":""30"",""Gender"":""Female""}]}"
Dim jss = New JavaScriptSerializer()
Dim data = jss.Deserialize(Of Object)(json)
Now, as an example, you could loop through the deserialized JSON and build an HTML table, like this:
Dim sb As New StringBuilder()
sb.Append("<table>" & vbLf & "<thead>" & vbLf & "<tr>" & vbLf)
' Build the header based on the keys of the first data item.
For Each key As String In data("items")(0).Keys
sb.AppendFormat("<th>{0}</th>" & vbLf, key)
Next
sb.Append("</tr>" & vbLf & "</thead>" & vbLf & "<tbody>" & vbLf)
For Each item As Dictionary(Of String, Object) In data("items")
sb.Append("<tr>" & vbLf)
For Each val As String In item.Values
sb.AppendFormat(" <td>{0}</td>" & vbLf, val)
Next
Next
sb.Append("</tr>" & vbLf & "</tbody>" & vbLf & "</table>")
Dim myTable As String = sb.ToString()
Disclaimer: I work with C# on a daily basis and this is a C# example using dynamic that was converted to VB.NET, please forgive me if there are any syntax errors with this.
Note:
First you have to install Newtonsoft.Json on nuget console. Then include following code on top of your code.
Imports Newtonsoft.Json
Step:1 Create class with get & set properties.
Public Class Student
Public Property rno() As String
Get
Return m_rno
End Get
Set(value As String)
m_rno = value
End Set
End Property
Private m_rno As String
Public Property name() As String
Get
Return m_name
End Get
Set(value As String)
m_name = value
End Set
End Property
Private m_name As String
Public Property stdsec() As String
Get
Return m_StdSec
End Get
Set(value As String)
m_StdSec = value
End Set
End Property
Private m_stdsec As String
End Class
Step: 2 Create string as a json format and conver as a json object model.
Dim json As String = "{'rno':'09MCA08','name':'Kannadasan Karuppaiah','stdsec':'MCA'}"
Dim stuObj As Student = JsonConvert.DeserializeObject(Of Student)(json)
Step: 3 Just traverses by object.entity name as follows.
MsgBox(stuObj.rno)
MsgBox(stuObj.name)
MsgBox(stuObj.stdsec)
Also, if you have complex json string. If there is subclasses, arrays, etc. in the json string, you can use this way at below. I tried it and it worked for me. I hope it will useful for you.
I accessed root->simpleforecast->forecastday[]->date->hight->celsius,fahrenheit values etc. in the json string.
Dim tempforecast = New With {Key .forecast = New Object}
Dim sFile As String = SimpleTools.RWFile.ReadFile("c:\\testjson\\test.json")
Dim root = JsonConvert.DeserializeAnonymousType(sFile, tempforecast)
Dim tempsimpleforecast = New With {Key .simpleforecast = New Object}
Dim forecast = jsonConvert.DeserializeAnonymousType(root.forecast.ToString(), tempsimpleforecast)
Dim templstforecastday = New With {Key .forecastday = New Object}
Dim simpleforecast = JsonConvert.DeserializeAnonymousType(forecast.simpleforecast.ToString(), templstforecastday)
Dim lstforecastday = simpleforecast.forecastday
For Each jforecastday In lstforecastday
Dim tempDate = New With {Key .date = New Object, .high = New Object, .low = New Object}
Dim forecastday = JsonConvert.DeserializeAnonymousType(jforecastday.ToString(), tempDate)
Dim tempDateDetail = New With {Key .day = "", .month = "", .year = ""}
Dim fcDateDetail = JsonConvert.DeserializeAnonymousType(forecastday.date.ToString(), tempDateDetail)
Weather_Forcast.ForcastDate = fcDateDetail.day.ToString() + "/" + fcDateDetail.month.ToString() + "/" + fcDateDetail.year.ToString()
Dim temphighDetail = New With {Key .celsius = "", .fahrenheit = ""}
Dim highDetail = JsonConvert.DeserializeAnonymousType(forecastday.high.ToString(), temphighDetail)
Dim templowDetail = New With {Key .celsius = "", .fahrenheit = ""}
Dim lowDetail = JsonConvert.DeserializeAnonymousType(forecastday.low.ToString(), templowDetail)
Weather_Forcast.highCelsius = Decimal.Parse(highDetail.celsius.ToString())
Weather_Forcast.lowCelsius = Decimal.Parse(lowDetail.celsius.ToString())
Weather_Forcast.highFahrenheit = Decimal.Parse(lowDetail.fahrenheit.ToString())
Weather_Forcast.lowFahrenheit = Decimal.Parse(lowDetail.fahrenheit.ToString())
Weather_Forcast09_Result.Add(Weather_Forcast)
Next

VB.net deserialize JSON with JSON.net

I look for a solution to my problem since 2 weeks without solution.
I would like to deserialize JSON with JSON.NET, but noway ...
I create class but when i deserialize the object stay empty (Nothing).
Here the JSON :
{"plannifReponse":
{"#competence":"Abonnement","plannifDonnees":
{"entry":
[
{"key":"2013-8-11T00:00","value":
{"creneaux":
[
{"#jour":"2013-8-11T00:00","#heure":"09","#minute":"30","nombreRessources":10},
{"#jour":"2013-8-11T00:00","#heure":"10","#minute":"30","nombreRessources":2},
{"#jour":"2013-8-11T00:00","#heure":"17","#minute":"30","nombreRessources":5},
{"#jour":"2013-8-11T00:00","#heure":"20","#minute":"30","nombreRessources":5},
{"#jour":"2013-8-11T00:00","#heure":"21","#minute":"00","nombreRessources":16}
]
}
},
{"key":"2013-7-30T00:00","value":
{"creneaux":
[{"#jour":"2013-7-30T00:00","#heure":"12","#minute":"00","nombreRessources":4},{"#jour":"2013-7-30T00:00","#heure":"12","#minute":"15","nombreRessources":10},{"#jour":"2013-7-30T00:00","#heure":"12","#minute":"30","nombreRessources":3},{"#jour":"2013-7-30T00:00","#heure":"14","#minute":"00","nombreRessources":8},{"#jour":"2013-7-30T00:00","#heure":"18","#minute":"30","nombreRessources":10}]}}]}}}
For this i translate with that Class:
Public Class plannifReponse
Public competence As String
Public plannifDonnees As Dictionary(Of String, ListCreneaux)
End Class
Public Class ListCreneaux
Public listCreneaux() As Creneau
End Class
Public Class Creneau
Public jour As String
Public heure As String
Public minute As String
Public nombreRessources As Integer
Public Sub New(ByVal _jour, ByVal _heure, ByVal _minute, ByVal _nombreRessources)
jour = _jour
heure = _heure
minute = _minute
nombreRessources = _nombreRessources
End Sub
End Class
And the code :
Dim prev As plannifReponse = JsonConvert.DeserializeObject(Of plannifReponse)(My_dispos)
But it doesn't work, no error message, but prev stay "Nothing"
For help, here the source object use to serialise (it is on Java)
public class OutputPlannif {
private String competence;
private HashMap<String, ListCreneaux> plannifDonnees;
}
public class ListCreneaux {
private ArrayList<Creneau> listCrenaux;
}
public class Creneau {
private String jour;
private String heure;
private String minute;
private int nombreRessources;
}
If anyone have an idea...
Thanks
Matt
You should create a series of classes which map the JSON you want to deserialize. There are tools (such as this one) which can do that for you. Or you can do it by hand, taking one member at a time, with the result shown below:
Public Class StackOverflow_17956746
Public Class OutputPlannif
<JsonProperty("plannifReponse")> _
Public PlannifReponse As PlannifReponse
End Class
Public Class PlannifReponse
<JsonProperty("#competence")> _
Public Competence As String
<JsonProperty("plannifDonnees")> _
Public PlannifDonnees As PlannifDonnees
End Class
Public Class PlannifDonnees
<JsonProperty("entry")> _
Public Entries As List(Of Entry)
End Class
Public Class Entry
<JsonProperty("key")> _
Public Key As String
<JsonProperty("value")> _
Public Value As Value
End Class
Public Class Value
<JsonProperty("creneaux")> _
Public ListCreneaux As List(Of Creneau)
End Class
Public Class Creneau
<JsonProperty("#jour")> _
Public Jour As String
<JsonProperty("#heure")> _
Public Heure As String
<JsonProperty("#minute")> _
Public Minute As String
<JsonProperty("nomberRessources")> _
Public NombreRessources As Integer
End Class
Const JSON As String = "{" & vbCrLf & _
" ""plannifReponse"":" & vbCrLf & _
"{""#competence"":""Abonnement"",""plannifDonnees"":" & vbCrLf & _
"{""entry"":" & vbCrLf & _
"[" & vbCrLf & _
"{""key"":""2013-8-11T00:00"",""value"":" & vbCrLf & _
"{""creneaux"":" & vbCrLf & _
"[" & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""09"",""#minute"":""30"",""nombreRessources"":10}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""10"",""#minute"":""30"",""nombreRessources"":2}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""17"",""#minute"":""30"",""nombreRessources"":5}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""20"",""#minute"":""30"",""nombreRessources"":5}," & vbCrLf & _
"{""#jour"":""2013-8-11T00:00"",""#heure"":""21"",""#minute"":""00"",""nombreRessources"":16}" & vbCrLf & _
"]" & vbCrLf & _
"}" & vbCrLf & _
"}," & vbCrLf & _
"{""key"":""2013-7-30T00:00"",""value"":" & vbCrLf & _
"{""creneaux"":" & vbCrLf & _
"[{""#jour"":""2013-7-30T00:00"",""#heure"":""12"",""#minute"":""00"",""nombreRessources"":4},{""#jour"":""2013-7-30T00:00"",""#heure"":""12"",""#minute"":""15"",""nombreRessources"":10},{""#jour"":""2013-7-30T00:00"",""#heure"":""12"",""#minute"":""30"",""nombreRessources"":3},{""#jour"":""2013-7-30T00:00"",""#heure"":""14"",""#minute"":""00"",""nombreRessources"":8},{""#jour"":""2013-7-30T00:00"",""#heure"":""18"",""#minute"":""30"",""nombreRessources"":10}]}}]}}}"
Public Shared Sub Test()
Dim output As OutputPlannif
output = JsonConvert.DeserializeObject(Of OutputPlannif)(JSON)
Console.WriteLine(output)
End Sub
End Class