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
Related
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())
I'm newbie in JSON, I made a first try with a file and it works fine. But my second file gives me headache.
The problem is that the second file start with this : [
my first file was like this
{
"GC": {
"Parameters": {
"feed": "gc",
"lang_code": "fr",
"fmt": "json",
} .................
I try many different things and I always have an error. The error is :
Additional information: Error converting value "person" to type 'JSonPerson'. Path '[0]', line 1, position 9.
Here's the second JSON file text (that start with the bracket "[" :
["person",
[{
"id": "19023",
"player_id": "16493",
"coach_id": "0",
"manager_id": "",
"official_id": ""
},
{
"id": "19024",
"player_id": "16494",
"coach_id": "1",
"manager_id": "",
"official_id": ""
}]]
Now my class:
Public Class JSonPerson
Public person As List(Of JSon_PersonDetail)
End Class
Public Class JSon_PersonDetail
Public id As String
Public player_id As String
Public coach_id As String
Public manager_id As String
Public official_id As String
Public user_id As String
Public first_name As String
Public last_name As String
End Class
And my code (that is the same for the first file, works perfect, but not with the second file):
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("c:\Global_files\person.json")
Dim reader2 As New StreamReader(stream)
Dim jsonData As String = reader2.ReadToEnd
Dim obj As List(Of JSonPerson)
obj = JsonConvert.DeserializeObject(Of List(Of JSonPerson))(jsonData)
I try this too:
Dim obj As JSonPerson
obj = JsonConvert.DeserializeObject(Of JSonPerson)(jsonData)
But I'm not able to push data inside my class I have errors:
Does someone know what's my problem ?
Update
I also tried reading directly from the stream using a JsonTextReader, like so:
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("c:Global_files\person.json")
Dim reader2 As New StreamReader(stream)
Dim jsonData As String = reader2.ReadToEnd
Dim reader As New JsonTextReader(reader2)
Dim people As JSonPeople
people = JsonSerializer.CreateDefault().Deserialize(Of JSonPeople)(reader)
reader2 have data. After the variable "reader" is empty. So the people is empty.
Here's the way I did it:
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("c:\Global_files\person.json")
Dim reader2 As New StreamReader(stream)
Dim jsonData As String = reader2.ReadToEnd
Dim jResults As JArray = JArray.Parse(jsonData)
'Here I know that is the children #1 that I need
Dim Data As List(Of JToken) = jResults.Item(1).Children().ToList
Dim vListOfPerson As New List(Of JSon_PersonDetail)
For Each item In Data
Dim ItemArray As Array = item.ToArray
Dim person As New JSon_PersonDetail
For Each element In ItemArray
Select Case element.name
Case "id"
person.id = element.value
Case "player_id"
person.player_id = element.value
Case "coach_id"
person.coach_id = element.value
Case "manager_id"
person.manager_id = element.value
Case "official_id"
person.official_id = element.value
Case "user_id"
person.user_id = element.value
Case "first_name"
person.first_name = element.value
Case "last_name"
person.last_name = element.value
End Select
Next
vListOfPerson.Add(person)
Next
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
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
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