Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 750
razz Avatar asked Apr 12 '13 19:04

razz


People also ask

How to get JSON response from REST API in ASP NET?

In this article I will explain with an example, how to get JSON response from REST API in ASP.Net using C# and VB.Net. The JSON response from the REST API will be read using WebClient class in ASP.Net using C# and VB.Net. The JSON.Net library is available for download from the following URL.

How to read JSON in VB NET?

You could refer to the following two thread that show how to read the JSON in vb.net. As the first one shows, you could first try to create some classes and then use the “JsonConvert.DeserializeObject (Of Container)” to parse the JSON data.

How do I parse JSON data from the web?

You’ve got several approaches to parsing data from the web which is in JSON format: You could write your own VBA code to parse the JSON data. This approach is only recommended if you have acute masochistic tendencies.

Is it possible to use JSON result in ASP NET?

Any help appreciated. Show activity on this post. PS. Make sure you have a reference to JSON.NET. Also, using .Result in ASP.NET is very problematic and can result easily in deadlocks.


2 Answers

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

like image 191
razz Avatar answered Nov 08 '22 20:11

razz


@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

like image 29
Rogala Avatar answered Nov 08 '22 18:11

Rogala