How to convert Json String to Json array in Visual Basic - vb.net

I am working UWP (Visual Basic) I am fetching data from one site which replies in JSON string format.
[
{"id": 1, "name": "Johny", "lname": "Sins", "phone": 123456789},
{"id": 2, "name": "Nike", "lname": "Jons", "phone": 23456789}
]
here is my code how I get it: -
Dim url As String = "http://127.0.0.1:8000/getdata/"
Dim Request As HttpWebRequest = HttpWebRequest.Create(url)
Request.Proxy = Nothing
Request.UserAgent = "Test"
Dim Response As HttpWebResponse = Request.GetResponse
Dim ResponseStream As System.IO.Stream = Response.GetResponseStream
Dim StreamReader As New System.IO.StreamReader(ResponseStream)
Dim Data As String = StreamReader.ReadToEnd
StreamReader.Close()
Now I want to print this data One by One in one text box, so how do I convert in to json array and print it?

I tested the parsing part with your Json data. Please refer to the method
Public Class node
Public Property id As Integer
Public Property name As String
Public Property lname As String
Public Property phone As Integer
End Class
Public Sub JsonTest()
Try
Dim json_test As String = "[
{'id': 1, 'name': 'Johny', 'lname': 'Sins', 'phone': 123456789},
{'id': 2, 'name': 'Nike', 'lname': 'Jons', 'phone': 23456789}
] "
Dim nodelist As List(Of node) = JsonConvert.DeserializeObject(Of List(Of node))(json_test)
For Each n In nodelist
Console.WriteLine(n.id)
Console.WriteLine(n.name)
Console.WriteLine(n.lname)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Related

problems reading a json already converted to object

I have the following json
{"24":[ { "data": "13", "moment": "07/20/2018" },{ "data": "16", "moment": "07/20/2018 0:15 :00" }]}
How would it be to go through it once read and converted to a json object using vbnet. I mean how to go through it
Update:
Dim request As WebRequest = WebRequest.Create(url_Final)
request.Method = "POST"
Dim Response As WebResponse = request.GetResponse()
Dim datastream = Response.GetResponseStream()
Dim reader As New StreamReader(datastream)
Dim responsefromServer = reader.ReadToEnd()
If responsefromServer = "0" Then
Console.Write("Fail json")
Else
Console.WriteLine(responsefromServer)
Dim result = JsonConvert.DeserializeObject(Of resultApi)(responsefromServer)
For Each magnitud In result
Console.WriteLine(magnitud)
Next
Console.ReadKey()
reader.Close()
Response.Close()
End If
Catch ex As Exception
Console.WriteLine(ex)
End Try
Update
Public Class resultApi
Public Property Magnitud As String
Public Property Sentilo As List(Of SentiloClass)
End Class
Public Class SentiloClass
Public Property data As Integer
Public Property moment As DateTime
End Class
Adding some classes created
Agree with Jimi's comment, if you've got varying key names that are carrying data that is important to you it's often easiest to just deser them to a dictionary so you can skip through it afterwards
Presumably you wanted a list of resultApi out of this
dim result = JsonConvert.DeserializeObject(Of Dictionary(Of String, List(Of SentiloClass)))(responsefromServer)
dim resultApis = result.Select( _
Function(kvp) _
New resultApi With {.Magnitud = kvp.Key, .Sentilo = kvp.Value} _
)

Cannot deserialise the JSON array

I'm working with VB.Net and can't manage to display the following JSON file in a datagridview.
{"files":[
{"file": "Test.out", "linecount": "4"},{"file": "test1.out", "linecount": "41"},{"file": "NocheinTest.out", "linecount": "41"}
]}
Can anyone help me with that?
here is the complete code
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim url As String
url = "http://...."
request = DirectCast(WebRequest.Create(url), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim s As String
s = reader.ReadToEnd
Dim files = JObject.Parse(s)("files").ToDictionary(Function(jt) jt("file").ToString(), Function(jt) Convert.ToInt32(jt("linecount")))
DataGridView1.DataSource = files.ToList()

VB.net - how do i get the response data from a website?

I'm trying to build a program that post data using "httpRequest.Post()" and am also trying to get the response data of the website, how do i go about it:
httpRequest.Referer = "https://website.com/"
Dim value As String = Regex.Match(httpRequest.[Get]("https://website.com/Login", Nothing).ToString(), "<input name=""Token"" type=""hidden"" value=""(.*?)"" />").Groups(1).ToString()
httpRequest.AddParam("Token", value)
httpRequest.AddParam("memberId", array(0))
httpRequest.AddParam("password", array(1))
httpRequest.AddParam("exp", "retail")
Dim text2 As String = httpResponse.Post("https://website/Login").ToString
If text2.Contains(" "Success" : true ") Or text2.Contains(" "memberPasswordValidationError" : false ") Then
If text2.Contains(" "Success" : true" ) Then
Me.successCode1 = "welcome"
ElseIf text2.Contains(" "memberPasswordValidationError" : false ") Then
Me.successCode2 = "Fail"
End If
End If
the response data looks like this
{
"memberPasswordValidationError" : false,
"Error" : null,
"Success" : false
}
The general pattern I have followed is
'Imports System.Net
Dim site As String
site = String.Format("https://website/Login?{0}={1}&{2}={3}&{4}={5}&{6}={7}",
"Token", "tokenvalue",
"memberId", "val",
"password", "passwd value",
"exp", "retail")
Dim request As WebRequest
request = WebRequest.Create(site)
request.Method = "POST" '<<<<<<<<<<<<<<<<
Dim data() As Byte = {}
request.ContentType = "application/x-www-form-urlencoded" '<<<<<<<<<<<<<<<<
request.ContentLength = data.Length
Dim stream As IO.Stream = request.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()
Dim response As WebResponse
response = request.GetResponse()
Dim sr As New IO.StreamReader(response.GetResponseStream())
Dim s As String
s = sr.ReadToEnd
You'll need to change some of this to match your variables. Hope it helps.

HttpClient to send JSON String Windows Form app

I'm writing a DLL but testing with a windows app and I have objects that I convert to JSON via
Private Function SeraializeStoreInfo(objt As JSON_postStoreInfo) As String
'This takes in an object of the JSON_postStoreInfo class
'and converts it to JSON to send
Dim JsonString As String
JsonString = JsonConvert.SerializeObject(objt)
Return JsonString
End Function
I then want to send this JSON string to a webservice to process. I just want to send the JSON string I've just serialized. When I pass the JasonString in as Content to this function as a string, I get an error saying that
HttpStringContent is not defined. and that Content must be of the type HttpContent.
How can a get around this?
Private Async Function SendStoreInfo(Content As String) As Task(Of String)
Dim stringContent As New HttpStringContent(Content, UnicodeEncoding.Utf8, "application/json")
Dim aClient As New HttpClient()
'Dim theContent As New StringContent(SR.ReadToEnd(), System.Text.Encoding.UTF8, "application/json")
' Dim theContent As New StringContent(Content, System.Text.Encoding.UTF8, "application/json")
'Post the data
Dim aResponse As HttpResponseMessage = Await aClient.PostAsync(theUrl, Content)
If (aResponse.IsSuccessStatusCode) Then
'this gets the response
StoreResponse = aResponse.ToString
Else
'show the response status code
Dim failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " – Reason: " + aResponse.ReasonPhrase
End If
End Function

How to read JSON http post response using VB

I have the following code, it connects to PHP server and retrieve data successfully, i'm not very good with VB, how can i read the JSON response text and extract it's elements?
Public Class Form1
Private Sub submit_Click(sender As System.Object, e As System.EventArgs) Handles submit.Click
Dim user As String
Dim pass As String
user = uname.Text
pass = passwd.Text
Dim request As WebRequest = WebRequest.Create("http://domain.com/test.php")
request.Method = "POST"
Dim postData As String
postData = "username=" & user & "&password=" & pass
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer = "0" Then
MsgBox("Login Failed")
Else
MsgBox("json data")
End If
reader.Close()
dataStream.Close()
response.Close()
End Sub
End Class
The JSON response would be something like:
{"comments": [
{
"comment" : "some text",
"date" : "some date",
"user" : "user name"
},
{
"comment" : "some text",
"date" : "some date",
"user" : "user name"
}
],
"messages": [ .... ]
}
How to output the json string into:
Comments
user date comment
-----------------------------------
user 1 date 1 comment 1
user 2 date 2 comment 2
Messages
user date message
-----------------------------------
user 1 date 1 message 1
user 2 date 2 message 2
After long research and many tests I found out a very nice extension called Newtonsoft.json, it's extremely simple and can be installed from package manager console like this:
install-package Newtonsoft.json
And include it like this:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Then all i needed to do is to declare the elements names and values like this:
Else
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 = ""
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "comments"
output += "Comments:" + vbCrLf
For Each comment As JObject In item.Values
Dim u As String = comment("user")
Dim d As String = comment("date")
Dim c As String = comment("comment")
output += u + vbTab + d + vbTab + c + vbCrLf
Next
Case "messages"
output += "Messages:" + vbCrLf
For Each msg As JObject In item.Values
Dim f As String = msg("from")
Dim t As String = msg("to")
Dim d As String = msg("date")
Dim m As String = msg("message")
Dim s As String = msg("status")
output += f + vbTab + t + vbTab + d + vbTab + m + vbTab + s + vbCrLf
Next
End Select
Next
MsgBox(output)
End If
hope someone will find this useful
#razzak is absolutely right to use the Json.Net NuGet package. Another option that would cut this down dramatically, is to use the built in DeserializeObject function. As long as you have a well define model, then you can deserialize the Json right into an instance of the object using something like this:
dim myObject as MyDefinedObject = JsonConvert.DeserializeObject(responseFromServer)
or this in C#
MyDefinedObject m = JsonConvert.DeserializeObject<MyDefinedObject>(responseFromServer);
Also, if you don't want to loop, you could also select tokens using something like this:
Dim d = ser.SelectToken("$..resources[?(#)].travelDistance")
This code above was used to locate the travelDistance between two points from the Bing API. If you have ever dealt with the Bing or Google Map REST APIs, then you know the JSon is generally too large to loop through the data when you are looking for very specific values.
The JSon.Net website has a blog page that goes through some additional examples:
http://james.newtonking.com/json
To use
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
'Json.Net' library should be installed.
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
This seems to cut it on VB.net for youtube API V.3
of course it depends on what you are trying to accomplish
but Youtube returns data as Json format