How to parse json and read in vb.net

I have this code in my project:

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

and TextBox2 gets the JSON code correctly.

and this is my JSON code example:

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

My question:

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


Solution 1:

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

Solution 2:

try this code :

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

hope it help you !!

Solution 3:

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.