Read JSON URL using Visual Basic .net - json

I'm trying to read URL containing JSON
Reading the file in the URL is ok, but when trying to parse the JSON I get an error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 2.
The code:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("http://phvarde.kundeside.dk/json?key=t6%$SVAKsG39"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As Object = JObject.Parse(rawresp)
TxtFornavn.Text = If(jResults("name") Is Nothing, "", jResults("name").ToString())
TxtAdresse.Text = If(jResults("address") Is Nothing, "", jResults("address").ToString())

You are getting this error because your JSON represents an array of objects, not just a single object. In this case you need to use JArray.Parse instead of JObject.Parse.
Dim array As JArray = JArray.Parse(json)
For Each item As JObject In array
Dim name As String = If(item("name") Is Nothing, "", item("name").ToString())
Dim address As String = If(item("address") Is Nothing, "", item("address").ToString())
// ... process name and address ...
Next
Fiddle: https://dotnetfiddle.net/2wfA17

Related

Get Json response from httpwebrequest in vb.net

Im working on an old VB.NET (ASP.NET) web page, and I need to get the response for an HttpWebRequest call as follows:
Dim s As HttpWebRequest
Dim enc As UTF8Encoding
Dim postdatabytes As Byte()
s = httpWebRequest.Create("www.theurl.com/api")
enc = New System.Text.UTF8Encoding()
Dim PostData = "grant_type=client_credentials"
postdata = postdata & "&client_id=" & ConfigurationManager.AppSettings("client_id")
postdata = postdata & "&client_secret=" & ConfigurationManager.AppSettings("client_secret")
postdata = postdata & "&audience=" & ConfigurationManager.AppSettings("audience")
postdatabytes = enc.GetBytes(postdata)
s.Method = "POST"
s.ContentType = "application/x-www-form-urlencoded"
s.ContentLength = postdatabytes.Length
Using stream = s.GetRequestStream()
stream.Write(postdatabytes, 0, postdatabytes.Length)
End Using
Dim result = s.GetResponse()
response.write(result)
The problem I have is that, instead of getting the Json string I get with Postman, I get this when response writing "result":
System.Net.HttpWebResponse
Any ideas?
Thanks!
For those looking for an answer, I made it work by adding the following code:
Dim responsedata As Stream = result.GetResponseStream
Dim responsereader As StreamReader = New StreamReader(responsedata)
Dim xResponse = responsereader.ReadToEnd
Response.Write(xResponse)
Thanks.

curl command in .net

I have a curl command I was given and trying to convert and use it in .net. I have tried many different scenarios but this was the closest one I thought would work. Anyone know what I am doing wrong? the response back si saying invalid API Key
Curl COMMAND = https://api.com/api/v1/scores --data "token=YOUR_API_TOKEN"
Dim request As HttpWebRequest = HttpWebRequest.Create("https://api.com/api/v1/groups")
request.Proxy = Nothing
request.Method = "GET"
request.ContentType = "application/json"
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(New ASCIIEncoding().GetBytes(String.Format("{0}={1}", "Token", personalaccesstoken))))
'create the response and reader
Dim Response As HttpWebResponse = request.GetResponse
Dim ResponseStream As System.IO.Stream = Response.GetResponseStream
'Create Stream reader
Dim StreamReader As New System.IO.StreamReader(ResponseStream)
Dim data As String = StreamReader.ReadToEnd
StreamReader.Close()
'get the data
jsonString = data.ToString.Replace("'", "''")
I ended up resolving this issue with the following code.
Dim request As HttpWebRequest = HttpWebRequest.Create(apiURI)
request.Proxy = Nothing
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = "token=22222222222222222"
Dim encoding As ASCIIEncoding = New ASCIIEncoding()
Dim byte1 As Byte() = encoding.GetBytes(postData)
request.ContentLength = byte1.Length
Dim newStream As Stream = request.GetRequestStream()
newStream.Write(byte1, 0, byte1.Length)
Dim Response As HttpWebResponse = request.GetResponse
Dim ResponseStream As System.IO.Stream = Response.GetResponseStream
'Create Stream reader
Dim StreamReader As New System.IO.StreamReader(ResponseStream)
_jsonString = StreamReader.ReadToEnd
StreamReader.Close()

How to HTML post with authorization token and JSON arguments in VB.NET

I'm creating a VB.NET program that I'd like to interface with dropbox. I'm starting with the "list_folder" command which will return the contents on a specified path. Here is the URL where you can play with the command:
https://dropbox.github.io/dropbox-api-v2-explorer/#files_list_folder
The HTTP request syntax provided is as follows:
POST /2/files/list_folder
Host: https://api.dropboxapi.com
User-Agent: api-explorer-client
Authorization: Bearer HBNBvdIls8AA12AAFTvyzhNJrdwwpQcswxpRVjmwRIJANPIea7Jc1Ke
Content-Type: application/json
{
"path": "/Backups"
}
What I'm trying to do is the equivalent in a VB.NET command. Here's what i have so far:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uri As String = "https://api.dropboxapi.com/2/files/list_folder"
Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(uri)
request.Method = "POST"
request.UserAgent = "api-explorer-client"
' this is wrong, need to supply an 'authorization token' somehow:
Dim credentials As New Net.NetworkCredential("username", "password")
request.Credentials = credentials
request.ContentType = "application/json"
'request.ContentLength = ???
' how do I set content to the "path: backups" data?
Dim response As Net.HttpWebResponse = request.GetResponse
Debug.Print(response.StatusDescription)
Dim dataStream As IO.Stream = response.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
Dim responseFromServer As String = reader.ReadToEnd() ' Read the content.
MsgBox(responseFromServer) ' Display the content.
' Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()
End Sub
What I'm missing is somehow encoding the "path": "/Backups" data specified by the doc into the request object. I'm also missing how to encode the "Authorization" access token into the request. (Above I'm using a username/password but that's probably wrong.)
Can anybody complete the VB.NET HTTP request for me? Thanks very much.
** UPDATE new code based on helpful links from the_lotus -- this works, thanks!:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uri As String = "https://api.dropboxapi.com/2/files/list_folder"
Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(uri)
request.Method = "POST"
request.UserAgent = "api-explorer-client"
request.Headers.Add("Authorization", "Bearer HBN-BvdIlsAAAFTyAQzhNJrBNINPIea7Jc1Ke")
'{
'"path": "/Backups"
'}
Dim json_data As String = "{"+ Chr(34) + "path" + Chr(34) + ": " + Chr(34) + "/Backups" + Chr(34) + "}"
request.ContentType = "application/json"
Dim json_bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(json_data)
request.ContentLength = json_bytes.Length
Dim stream As IO.Stream = request.GetRequestStream
stream.Write(json_bytes, 0, json_bytes.Length)
Dim response As Net.HttpWebResponse = request.GetResponse
Debug.Print(response.StatusDescription)
Dim dataStream As IO.Stream = response.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
Dim responseFromServer As String = reader.ReadToEnd() ' Read the content.
MsgBox(responseFromServer) ' Display the content.
' Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()
End Sub
You can add custom header with request.Headers.
request.Headers.Add("Authorization", "Bearer HBN-BvdIlsAAAFTyAQzhNJrBNINPIea7Jc1Ke")
To send the POST information, you can use request.GetRequestStream.
Also, make sure the data send in the POST is properly formatted JSON.

Box.Net Create Folder Bad Request 400

Dim url As String = String.Format("{0}folders/{1}", boxApiUrl, ParentFolderId) 'ParentFolderId being pass is "0"
Using request = New HttpRequestMessage() With {.RequestUri = New Uri(url), .Method = HttpMethod.Post}
request.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Bearer " + acctoken)
Dim data As Dictionary(Of [String], [String]) = New Dictionary(Of String, String)()
data.Add("name", FolderName)
Dim content As HttpContent = New FormUrlEncodedContent(data)
request.Content = content
Dim response = _httpClient.SendAsync(request).Result
If response.IsSuccessStatusCode Then
'
End If
End Using
My suspicion is that data is not being put together properly but can't figure out how else to pass folder name to be created under the root. All other functions (reading root folder, uploading file, etc.) using the token works fine.
The parent folder ID is passed in the POST body, not the URL. The body should be JSON data in the form: { "name": "FolderName", "parent": { "id": "ParentFolderId" }}. Documentation.
Dim url As String = String.Format("{0}folders", boxApiUrl)
Using request = New HttpRequestMessage() With {.RequestUri = New Uri(url), .Method = HttpMethod.Post}
request.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Bearer " + acctoken)
Dim format as String = #"{{ ""name"":""{0}"", ""parent"": {{ ""id"":""{1}"" }} }}";
Dim body as String = String.Format(format, FolderName, ParentFolderId);
request.Content = New StringContent(body, Encoding.UTF8, "application/json")
Dim response = _httpClient.SendAsync(request).Result
If response.IsSuccessStatusCode Then
'
End If
End Using
As an aside, you can use Json.NET's JsonConvert.SerializeObject method to serialize an anonymous or static type to a JSON string:
Dim obj = New With {Key .name = FolderName,
.parent = New With {Key .id = ParentFolderId }};
Dim body as String = JsonConvert.SerializeObject(body);
request.Content = New StringContent(body, Encoding.UTF8, "application/json")

Newtonsoft.Json.JsonReaderException

I have a problem with Newtonsoft.Json. I'm trying to parse JSON from a URL but I'm getting an error. Here is the JSON:
[
{
"ID": "0",
"Nome": "we",
"Data": "2013-09-16",
"Orario": "00:00:16",
"Prestazione": "dfg",
"Stato": "dfg",
"Numero_Telefono": "dfg"
},
{
"ID": "0",
"Nome": "fg",
"Data": "2013-09-26",
"Orario": "00:00:00",
"Prestazione": "",
"Stato": "",
"Numero_Telefono": ""
},
{
"ID": "1",
"Nome": "davide",
"Data": "2013-09-26",
"Orario": "00:00:16",
"Prestazione": "ds",
"Stato": "sd",
"Numero_Telefono": "3546"
}
]
Here is the code I am using:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://nhd.altervista.org/connectDb.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JProperty In results
item.CreateReader()
MsgBox(item.Value("img")) ' because my tag in json is img
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
This is the error I receive when I try to parse the JSON:
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Can you help me solve this?
You are getting this error because you are using JObject.Parse, which expects a single JSON object, but your JSON contains an array. To correct this, use JArray.Parse instead.
But, there is another problem: the rest of your code is not set up to handle the results correctly. Because your results are an array of objects, your For Each loop needs to be expecting JObject items, not JProperty items. Once you have each item, you can then get the properties from them as needed.
I am not sure what you were trying to do with the item.CreateReader() line, as you are not doing anything with its return value, and you don't seem to need anyway. Similarly, I am also confused with your MsgBox(item.Value("img")) line, because there is no "img" property anywhere in the JSON. So this will always be null.
Here is some corrected code which will parse the JSON and display all the properties for each object in the results. This should give you a starting point to work with.
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://nhd.altervista.org/connectDb.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JArray = JArray.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JObject In results
Dim demo As String = ""
For Each prop As JProperty In item.Properties()
demo = demo + prop.Name + " = " + prop.Value.ToString() + vbCrLf
Next
MsgBox(demo)
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try