16

我有以下代码,它连接到 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

4 回答 4

24

经过长时间的研究和多次测试,我发现了一个非常好的扩展名为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

希望有人会觉得这很有用

于 2013-04-14T19:17:08.073 回答
8

@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

于 2014-04-09T17:14:25.100 回答
2

使用

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

应该安装“Json.Net”库。

截屏

于 2016-07-14T21:48:22.907 回答
0
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

这似乎在 VB.net 上针对 youtube API V.3 进行了削减
,当然这取决于您要完成的工作,但 Youtube 以 Json 格式返回数据

于 2015-09-18T22:28:25.450 回答