如何解析json并在vb.net中读取

Ali*_*ami 9 vb.net json

我在我的项目中有这个代码:

Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader

request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)

response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())

Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = rawresp
Run Code Online (Sandbox Code Playgroud)

和TextBox2正确获取JSON代码.

这是我的JSON代码示例:

{
  "id":174543706,
  "first_name":"Hamed",
  "last_name":"Ap",
  "username":"hamed_ap",
  "type":"private"
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

如何从JSON代码("id")获取174543706到TextBox3.Text ???

Jim*_*itt 9

你可以使用JavaScriptSerializer哪个System.Web.Script.Serialization.

Imports System.Web.Script.Serialization

Module Module1
    Sub Main()

        Dim s As String

        Try
            Dim rawresp As String = "{""id"":174543706,""first_name"":""Hamed"",""last_name"":""Ap"",""username"":""hamed_ap"",""type"":""private""}"

            Dim jss As New JavaScriptSerializer()
            Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)

            s = dict("id")
        Catch ex As Exception

        End Try

    End Sub

End Module
Run Code Online (Sandbox Code Playgroud)

  • @Ali添加对`System.Web.Extensions`的引用. (4认同)

Med*_*ane 5

试试这个代码:

Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
Dim firstItem = jsonResulttodict.item ("id") 
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助!