我有以下代码,它连接到
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,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","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
经过长时间的研究和许多测试,我发现一个非常好的扩展名为Newtonsoft.json,它非常简单,可以从包管理器控制台安装如下:
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
希望有人会发现这有用
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。