如何使用VB读取JSON http post响应

时间:2013-04-12 19:48:46

标签: vb.net visual-studio-2010

我有以下代码,它连接到PHP服务器并成功检索数据,我对VB不是很好,我怎样才能读取JSON响应文本并提取它的元素?

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

JSON响应类似于:

{"comments": [
               {
               "comment" : "some text",
               "date"    : "some date",
               "user"    : "user name"
               },
               {
               "comment" : "some text",
               "date"    : "some date",
               "user"    : "user name"
               }
             ],
 "messages": [ .... ]
}

如何将json字符串输出到:

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

4 个答案:

答案 0 :(得分:22)

经过长时间的研究和许多测试,我发现了一个名为Newtonsoft.json的非常好的扩展,它非常简单,可以从package manager console安装,如下所示:

install-package Newtonsoft.json

并将其包括在内:

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

然后我需要做的就是声明元素名称和值,如下所示:

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

希望有人能找到这个有用的

答案 1 :(得分:6)

@razzak绝对正确使用Json.Net NuGet包。另一个可以大幅减少这种情况的选择是使用内置的DeserializeObject函数。只要您有一个良好定义的模型,那么您可以使用以下内容将Json反序列化为对象的实例:

dim myObject as MyDefinedObject = JsonConvert.DeserializeObject(responseFromServer)

或在C#

MyDefinedObject m = JsonConvert.DeserializeObject<MyDefinedObject>(responseFromServer);

此外,如果您不想循环,您还可以使用以下内容选择令牌:

Dim d = ser.SelectToken("$..resources[?(@)].travelDistance")

上面的代码用于定位Bing API中两点之间的travelDistance。如果您曾经处理过Bing或Google Map REST API,那么您知道当您查找非常具体的值时,JSon通常太大而无法遍历数据。

我希望这对想要做这样的事情的人有所帮助。 JSon.Net网站有一个博客页面,其中包含一些其他示例。

http://james.newtonking.com/json

〜干杯

答案 2 :(得分:2)

使用

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

应安装'Json.Net'库。

screenshot

答案 3 :(得分:0)

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

这似乎在VB.net上针对youtube API V.3进行了削减
当然这取决于你想要完成什么 但是Youtube以Json格式返回数据