Read JSON URL using Visual Basic .net

23,296

You are getting this error because your JSON represents an array of objects, not just a single object. In this case you need to use JArray.Parse instead of JObject.Parse.

Dim array As JArray = JArray.Parse(json)

For Each item As JObject In array
    Dim name As String = If(item("name") Is Nothing, "", item("name").ToString())
    Dim address As String = If(item("address") Is Nothing, "", item("address").ToString())
    // ... process name and address ...
Next

Fiddle: https://dotnetfiddle.net/2wfA17

Share:
23,296
Admin
Author by

Admin

Updated on September 03, 2020

Comments

  • Admin
    Admin over 3 years

    I'm trying to read URL containing JSON
    Reading the file in the URL is ok, but when trying to parse the JSON I get an error:

    An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
    Additional information: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 2.
    

    The code:

        Dim request As HttpWebRequest  
        Dim response As HttpWebResponse = Nothing  
        Dim reader As StreamReader  
    
        request = DirectCast(WebRequest.Create("http://phvarde.kundeside.dk/json?key=t6%$SVAKsG39"), HttpWebRequest)
    
        response = DirectCast(request.GetResponse(), HttpWebResponse)
        reader = New StreamReader(response.GetResponseStream())
    
        Dim rawresp As String
        rawresp = reader.ReadToEnd()
    
        Dim jResults As Object = JObject.Parse(rawresp)
        TxtFornavn.Text = If(jResults("name") Is Nothing, "", jResults("name").ToString())
        TxtAdresse.Text = If(jResults("address") Is Nothing, "", jResults("address").ToString())
    
  • Admin
    Admin over 8 years
    How can I implement you solution using an array?? The code: Dim jsonstr As String = File.ReadAllText("c:\temp\json.json") Dim jResults As JObject = JObject.Parse(jsonstr) Dim results As Generic.List(Of JToken) = jResults.Children().ToList() For Each item As JProperty In results item.CreateReader() Select Case item.Name Case "name" TxtFornavn.Text = item.Value.ToString End select
  • Brian Rogers
    Brian Rogers over 8 years
    I'm not sure I understand what you are trying to do. Can you edit your question to clarify? Putting code in the comments section doesn't work very well.
  • Admin
    Admin over 8 years
    I'm trying to get one record at a time and display it in a windowsform. When the first data has been approved we will send it to an SQL database and the NeXT record should load to the windowsform.
  • Brian Rogers
    Brian Rogers over 8 years
    This sounds like a different issue. I would recommend opening a new question.