I'm having a problem with JSON deserialization hope you can help me.
I have a JSON that have the following information:
{
"object":"list",
"more":false,
"data":[
{
"object":"number",
"id":"1",
"code":"1",
"name":"One",
},
{
"object":"number",
"id":"2",
"code":"2",
"name":"Two",
}
...
So I've a created a simple app so I can use that information:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim uri As New Uri(uriString)
'Make Request
Dim Request As HttpWebRequest = HttpWebRequest.Create(uri)
Request.Method = "GET"
'Get Response
Dim Response As HttpWebResponse = Request.GetResponse()
'Read Response
Dim Read = New StreamReader(Response.GetResponseStream())
Dim Raw As String = Read.ReadToEnd()
'Convert response
Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(Raw)
For Each item In dict
MsgBox(item)
MsgBox(item("code"))
TextBox1.Text += item("code").ToString + " - " + item("name").ToString + vbNewLine
Next
End Sub
It seems I get the response, since the Read I get the JSON, but after that, I can't get the information listed in that JSON. What I'm doing wrong?
You are not de-serializing properly. Your dict is empty like that.
This will work as intended.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim Request As HttpWebRequest = WebRequest.Create(New Uri(uriString))
Dim JSON_Response As String = New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd()
Dim JSON_Obj1 As Object = New JavaScriptSerializer().DeserializeObject(JSON_Response)
Dim Test1 as String = JSON_Obj1("data")(0)("code")
For Each item In JSON_Obj1("data")
Debug.Print(item("code"))
Next
End Sub
Related
I have a JSON that I want to deserialize.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As New RestClient(BaseUrl)
Dim Respons As Object
client.Authenticator = OAuth1Authenticator.ForProtectedResource(PublicKey, PrivateKey, Token, TokenSecret)
Dim request As New RestRequest("xml/devices/list", Method.Get)
Respons = client.Execute(request)
Console.WriteLine(Respons.Content)
Console.ReadLine()
Dim request2 As New RestRequest("json/sensor/history?id=1556402310&IncludeUnit=1&InculdeHumanReadableDate=1", Method.Get)
Respons = client.Execute(request2)
Console.WriteLine(Respons.Content)
Console.ReadLine()
End Sub
So the JSON is in Respons, but I haven't a clue how to deserialize it
Have not done anything because I don't know how.
This is how the JSON looks like
Something like this:
Public Class Sensor_class
Public Property thing As Integer
Public Property thing2 As Object
Public Property results As Result()
End Class
Dim o as Sensor_class
o = JsonConvert.DeserializeObject(Of Sensor_class)(Respons.Content)
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 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")
Is there any possible way to convert direct url to json into xml as text into one textbox?
Example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Json1 as string = "http://pastebin.com/raw.php?i=p3uBzBtm"
Dim jss = New JsonSerializer()
Dim response2 = jss.Deserialize(Of Object)(Json1)
textbox1.text = response2
End Sub
Sorry for this bad example, I'm newbie in this language.
Use this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Json1 As String = New WebClient().DownloadString("http://pastebin.com/raw.php?i=p3uBzBtm")
Dim str = JsonConvert.DeserializeXmlNode(Json1)
TextBox1.Text = str.OuterXml
End Sub
For multiple nodes you will want something like this:
Dim Json1 As String = "{ 'root': " & New WebClient().DownloadString("http://pastebin.com/raw.php?i=ugZrw4d6") & " }"
Dim doc As XmlDocument = JsonConvert.DeserializeXmlNode(Json1)
Dim result As String = doc.ChildNodes(0).InnerXml
TextBox1.Text = result
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