How to parse json and read in vb.net

后端 未结 4 1083
独厮守ぢ
独厮守ぢ 2020-11-29 11:23

I have this code in my project:

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

request = DirectCast(Web         


        
相关标签:
4条回答
  • 2020-11-29 11:38

    You could use JavaScriptSerializer which is in 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
    
    0 讨论(0)
  • 2020-11-29 11:38

    This works:

    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 = JObject.Parse(rawresp)("id")
    
    0 讨论(0)
  • 2020-11-29 11:44

    How to get 174543706 from JSON code ("id") into TextBox3.Text?

    {
      "id": 174543706,
      "first_name": "Hamed",
      "last_name": "Ap",
      "username": "hamed_ap",
      "type": "private"
    }
    

    Sorry if my reply was late. I hope my answer can help someone who's still confused. So what you do was get the response and read the JSON.

    After you do ReadToEnd():

    Dim xr As XmlReader = XmlReader.Create(New StringReader(rawresp))
    Dim doc As XmlDocument = New XmlDocument()
    doc.LoadXml(rawresp)
    

    Then What you need to do is to read the data from the response. you do like this:

    Dim res As String = JsonConvert.SerializeXmlNode(doc)
    Dim ThisToken As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(res)
    Dim response As String = ThisToken("response").ToString()
    Dim ThisData As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(response)
    

    After that yo can get the data from the response and convert it into string

    Dim idx As String = ThisData("id").ToString()
    
    // the value of idx will be: 174543706
    

    Then last you can put it into Texbox3.Text.

    0 讨论(0)
  • 2020-11-29 11:57

    try this code :

    Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
    Dim firstItem = jsonResulttodict.item ("id") 
    

    hope it help you !!

    0 讨论(0)
提交回复
热议问题