2

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())
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Steen Sommer
  • 33
  • 1
  • 1
  • 5
  • 2
    possible duplicate of [Deserializing JSON in Visual Basic .NET](http://stackoverflow.com/questions/31905958/deserializing-json-in-visual-basic-net) – AStopher Sep 02 '15 at 09:39

1 Answers1

1

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

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • 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 – Steen Sommer Sep 03 '15 at 10:40
  • 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. – Brian Rogers Sep 03 '15 at 15:09
  • 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. – Steen Sommer Sep 04 '15 at 16:51
  • This sounds like a different issue. I would recommend opening a new question. – Brian Rogers Sep 04 '15 at 20:05