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())
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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
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.
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.
This sounds like a different issue. I would recommend opening a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.