Wednesday, December 7, 2016

Read JSON Data using VB.Net

First, add reference the DLL file from this URL: https://www.dllme.com/dll/files/newtonsoft_json_dll.html

 Then imports these,
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Now we can get the JSON file data in the Textbox,
Private Sub Button1_Click ()
        Dim address As String{JSON API/File}
        Dim client As WebClient = New WebClient()
        Dim reply As String = client.DownloadString(address)
        TextBox1.Text = reply
End Sub

Now we can get the each single Child node Data Value,
Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Grand_Node").SelectToken("Father_Node").SelectToken("Child_Node"))
MsgBox(json.SelectToken("Grand_Node.Father_Node.Child_Node"))

Now we can get the each single Child node Data Value using Loop
    Private Sub Button2_Click()
        Dim json As JObject = JObject.Parse(TextBox1.Text)
        Dim results As List(Of JToken) = json.Children().ToList

        Dim Sec1 As String
        Dim Sec2 As String
        Dim Sec3 As String
        Dim Ans1 As String
        Dim Ans2 As String
        Dim Ans3 As String

        For Each item As JProperty In results
            item.CreateReader()
            Select Case item.Name
                Case "questions"
                    For Each subitem As JObject In item.Values
                           Sec1 = subitem("section1")
                           MsgBox(Sec1)
                            Sec2 = subitem("section2")
MsgBox(Sec2)
                            Sec3 = subitem("section3")
MsgBox(Sec3)
                     Next

                Case "responses"
                    For Each subitem As JObject In item.Values
Ans1 = subitem("answer1")
MsgBox(Ans1)
                            Ans2 = subitem("answer2")
MsgBox(Ans2)
                            Ans3 = subitem("answer3")
MsgBox(Ans3)
                    Next
            End Select

        Next
    End Sub

No comments:

Post a Comment