how to parse json in vb.net - json

I have json: {'success':'1','return':[{'id':'32928888','datetime':'2014-03-25 02:49:21','price':'0.02800939','quantity':'0.26094649','total':'0.00730895','io':'Buy'},{'id':'32928884','datetime':'2014-03-25 02:49:18','price':'0.02800939','quantity':'0.09930853','total':'0.00278157','io':'Buy'},{'id':'32928850','datetime':'2014-03-25 02:48:49','price':'0.02800939','quantity':'0.00093585','total':'0.00002621','io':'Buy'},{'id':'32928848','datetime':'2014-03-25 02:48:48','price':'0.02800939','quantity':'0.23547262','total':'0.00659544','io':'Sell'},{'id':'32928698','datetime':'2014-03-25 02:47:42','price':'0.02800939','quantity':'0.25553470','total':'0.00715737','io':'Sell'},{'id':'32928540','datetime':'2014-03-25 02:47:05','price':'0.02800940','quantity':'0.00820048','total':'0.00022969','io':'Sell'}]}
and I use code:
Public Function parse_json(ByVal json As String) As Nullable
Try
Dim jResults As JObject = JObject.Parse(json)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JProperty In results
item.CreateReader()
MsgBox(item.Value("id"))
MsgBox(item.Value("datetime"))
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Function
But I get error saying: System.InvalidOperationException: Cannot access child value on Newtonsoft.Json.Linq.JValue. What am I doing wrong? I need to get all ids, prices and so on.

return is the child of the full object:
Dim results As JArray = jResults.GetValue("return");

I changed the codes which is tested working as:
Public Function parse_json(ByVal json As String) As Nullable
Try
Dim jResults As JObject = JObject.Parse(json)
' Dim results As List(Of JToken) = jResults.Children().ToList()
Dim arrResult As JArray = jResults.GetValue("return")
For Each item As JObject In arrResult
'item.CreateReader()
'MsgBox(item.Value("id"))
'MsgBox(item.Value("datetime"))
Dim strid As String = item.GetValue("id")
Dim strdt As String = item.GetValue("datetime")
Diagnostics.Debug.WriteLine("id: " & strid)
Diagnostics.Debug.WriteLine("dt: " & strdt)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Function

Related

How to get all subnodes in a JSON file using JSON.Net

I wan't to get all subnodes in a JSON file using JSON.NET is it possible ?
Here is my code :
Shared Function LoadBranch(ByVal branch As String, ByVal tv As TreeView)
Dim jsonstr As String = FileIO.FileSystem.ReadAllText(FileIO.FileSystem.ReadAllText(".\temp\localpath.txt"))
Dim obj As JObject = JObject.Parse(jsonstr)
Dim result As List(Of JToken) = obj.Children().ToList()
For Each item As JProperty In result
Dim rootName As String = item.Name
If branch = rootName Then
Dim root As TreeNode = tv.Nodes.Add(rootName)
For Each child In item.Children()
For Each jprop As JProperty In child
root.Nodes.Add(String.Format("{0} : {1}", jprop.Name, jprop.Value))
Next
Next
End If
Next
Return True
End Function

VB.NET Fill DataGridView from JSON

I am struggling to fill a DataGridView from a JSON that I get through a webrequest to SOLR.
JSON Example:
{
"response":{"numFound":6,"start":1,"docs":[
{
"PRODUCTNAME":"Office Chair",
"CURRENCYCODE":"EUR",
"CLIENTCODE":"Northwind Inc",
"LANGUAGECODE":"ENG",
"KEYWORDS":"spins, adjust, castors"}]
}}
The below will work and get one token and put it in a label.
Code:
Private Sub SOLR()
Label2.Text = Nothing
Try
Dim fr As WebRequest
Dim targetURI As New Uri("LinkToJson")
fr = DirectCast(WebRequest.Create(targetURI), WebRequest)
fr.Credentials = New NetworkCredential("admin", "admin")
If (fr.GetResponse().ContentLength > 2) Then
Dim str As New StreamReader(fr.GetResponse().GetResponseStream())
Dim streamText As String = str.ReadToEnd()
Dim myJObject = JObject.Parse(streamText)
Label2.Text = myJObject.SelectToken("response.docs[0].KEYWORDS")
Label3.Text = streamText
End If
Catch ex As WebException
MessageBox.Show(ex.ToString())
End Try
End Sub
I tried to deserialize it, but I get an error for the below:
Dim table As DataTable = JsonConvert.DeserializeObject(Of DataTable)(streamText)
DataGridView1.DataSource = myJObject
Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.'
You need to pass the "docs" array to the DeserializeObject function in order to load the JSON data into DataTable.
Dim myJObject = JObject.Parse(streamText)
Dim arr = myJObject("response")("docs")
Dim table = JsonConvert.DeserializeObject(Of DataTable)(arr.ToString())

How to parse json and read in vb.net

I have this code in my project:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = rawresp
and TextBox2 gets the JSON code correctly.
and this is my JSON code example:
{
"id":174543706,
"first_name":"Hamed",
"last_name":"Ap",
"username":"hamed_ap",
"type":"private"
}
My question:
How to get 174543706 from JSON code ("id") into TextBox3.Text???
You could use JavaScriptSerializer which is in System.Web.Script.Serialization.
Imports System.Web.Script.Serialization
Module Module1
Sub Main()
Dim s As String
Try
Dim rawresp As String = "{""id"":174543706,""first_name"":""Hamed"",""last_name"":""Ap"",""username"":""hamed_ap"",""type"":""private""}"
Dim jss As New JavaScriptSerializer()
Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)
s = dict("id")
Catch ex As Exception
End Try
End Sub
End Module
try this code :
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
Dim firstItem = jsonResulttodict.item ("id")
hope it help you !!
How to get 174543706 from JSON code ("id") into TextBox3.Text?
{
"id": 174543706,
"first_name": "Hamed",
"last_name": "Ap",
"username": "hamed_ap",
"type": "private"
}
Sorry if my reply was late. I hope my answer can help someone who's still confused.
So what you do was get the response and read the JSON.
After you do ReadToEnd():
Dim xr As XmlReader = XmlReader.Create(New StringReader(rawresp))
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(rawresp)
Then What you need to do is to read the data from the response. you do like this:
Dim res As String = JsonConvert.SerializeXmlNode(doc)
Dim ThisToken As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(res)
Dim response As String = ThisToken("response").ToString()
Dim ThisData As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(response)
After that yo can get the data from the response and convert it into string
Dim idx As String = ThisData("id").ToString()
// the value of idx will be: 174543706
Then last you can put it into Texbox3.Text.
JSON can be parsed using adding Newtonsoft.Json.dll reference
Code :
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim json As String = New System.Net.WebClient().DownloadString("http://time.jsontest.com/")
Dim parsejson As JObject = JObject.Parse(json)
Dim thedate = parsejson.SelectToken("date").ToString()
txt1.Text = "Date Is "+thedate
End Sub
End Class
Reference : Narendra Dwivedi - Parse JSON
This works:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = JObject.Parse(rawresp)("id")

De-serializing JSON data in vb

I have been trying to deserialize JSON data, and this is how far I have gotten before searching StackOverflow and I followed an article however it still broke. I'm getting a runtime error on this line:
Dim jsonObject As Newtonsoft.Json.Linq.JArray = JsonConvert.DeserializeObject(json)
Stating "Can not convert Object to String."
Thanks in advance :D
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Structure JSONList
Dim URL, Name As String
End Structure
Public Class Form1
Dim JSONList As List(Of ListViewItem)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim request As WebRequest = WebRequest.Create("http://www.reddit.com/r/EarthPorn.json")
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
MessageBox.Show(responseFromServer)
Dim json As String = responseFromServer
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim jsonObject As Newtonsoft.Json.Linq.JArray = JsonConvert.DeserializeObject(json)
Dim JSONDecode() As JSONList = (From j In jsonObject
Select New JSONList() With {.URL = j("URL"),
.Name = j("Name")}
).ToArray()
MessageBox.Show(JSONDecode(0).Name)
End Sub
End Class

vb.net datatable Serialize to json

I have this kind of table:
I need to get this JSON (of course order could be any, structure/tree is most important):
Data table can change, so serialization should be dynamic. I am working with vb.net and used this code:
Public Function GetJson() As String
Dim dt As New System.Data.DataTable
dt = CreateDataTable() 'here I retrive data from oracle DB
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim packet As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object) = Nothing
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each dc As DataColumn In dt.Columns
row.Add(dc.ColumnName.Trim(), dr(dc))
Next
packet.Add(row)
Next
Return serializer.Serialize(packet)
End Function
But this code returns me bad json: [{"NAME":"city","PARENT":"address","VALUE":"has child"},{"NAME":"coordinates","PARENT":"address","VALUE":"has child"},{"NAME":"street","PARENT":"address","VALUE":"has child"}.......
Can someone help me out in here?
The 'Oh-no you didn't' version:
Public Function GetJson(ByVal dt As DataTable) As String
Return New JavaScriptSerializer().Serialize(From dr As DataRow In dt.Rows Select dt.Columns.Cast(Of DataColumn)().ToDictionary(Function(col) col.ColumnName, Function(col) dr(col)))
End Function
Here is my solution:
Public Function GetJson() As String
Dim dt As New System.Data.DataTable
dt = CreateDataTable() 'here I retrive data from oracle DB
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim packet As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object) = Nothing
Try
Dim result() As DataRow = dt.Select("Parent_ = 'main'")
Dim i As Integer
For i = 0 To result.GetUpperBound(0)
row = New Dictionary(Of String, Object)()
If UCase(result(i)(2)) <> "HAS CHILD" Then
row.Add(result(i)(0), result(i)(2))
Else
row.Add(result(i)(0), add_(dt, result(i)(0)))
End If
packet.Add(row)
Next i
Return serializer.Serialize(packet)
Catch ex As Exception
MsgBox(ex.ToString)
Me.Close()
End Try
End Function
Public Function add_(ByVal dt As System.Data.DataTable, ByVal parent_ As String) As Dictionary(Of String, Object)
Dim row As Dictionary(Of String, Object) = Nothing
Try
Dim result() As DataRow = dt.Select("Parent_ = '" & parent_ & "'")
Dim i As Integer
row = New Dictionary(Of String, Object)()
For i = 0 To result.GetUpperBound(0)
If UCase(result(i)(2)) <> "HAS CHILD" Then
row.Add(result(i)(0), result(i)(2))
Else
row.Add(result(i)(0), add_(dt, result(i)(0)))
End If
Next i
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return row
End Function