我正在尝试读取包含JSON的URL
在URL中读取文件是可以的,但是当试图解析JSON时,我得到一个错误:
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.
代码:
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())
您得到这个错误是因为您的JSON表示对象数组,而不仅仅是单个对象。在这种情况下,您需要使用JArray.Parse
而不是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
小提琴:https://dotnetfiddle.net/2wfA17