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")
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 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
Here is the JSON content that needs to be posted.
{
"getcart": {
"version": "1.0",
"account": "6566",
"username": "112",
"password": "xxxxxxxx",
"cartid": "57044d79",
} }
Code:
Dim jsonPost As New JsonPost("https://www.example.aspx")
Dim dictData As New Dictionary(Of String, Object)
dictData.Add("version", "1.0")
dictData.Add("account", "6566")
dictData.Add("username", "112")
dictData.Add("password", "xxxxxxxx")
dictData.Add("cartid", "57044d79")
Dim json As JObject = JObject.Parse(JsonPost.postData(dictData))
Dim response As String = JsonPost.postData(dictData)
MsgBox(response)
The error I'm getting:
Error reading JObject from JsonReader. Path'',line 0 postion 0
How can I fix this?
I couldn't do it using the dictionary. But I was able to post it as a string.
The main issue was declaring a JSON string that contains an object in Visual Basic. Here is how I did it:
Dim JsonData As String = "{'getcart':{
'version':'1.0',
'account':'6566',
'username':'112',
'password':'xxxxxxxx',
'cartid':'57044d79',
}}"
Dim Uri As String = "https://www."
Dim data = Encoding.UTF8.GetBytes(JsonData)
Dim result_post = SendRequest(New Uri(Uri), data, "application/json", "POST")
MsgBox(result_post)
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
this is the code i have, dim sline from string to json, i have try it and search on google, but i havent done yet...
please help
Dim sURL As String
sURL = TextBox1.Text
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True
wrGETURL.Proxy = myProxy
wrGETURL.Proxy = WebProxy.GetDefaultProxy()
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0
Do While Not sLine Is Nothing
i += 1
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
Console.WriteLine("{0}:{1}", i, sLine)
End If
Loop
Dim respon As Array = sLine.ToArray()
Console.ReadLine()
Console.WriteLine(respon("traceNo"))
Console.ReadLine()
i want to convert the Dim sline to json, how it possible?
Newtonsoft.JSON is a VERY handy NuGet to easy use JSON in VB.Net.
Seperate your lines into a List(Of Integer, String) (i,sLine)
and Serialize it with
Dim yourJSONString = JsonConvert.SerializeObject(yourList)
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