vb.net 使用 Visual Basic .net 读取 JSON URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32349575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:26:16  来源:igfitidea点击:

Read JSON URL using Visual Basic .net

jsonvb.netjson.net

提问by Steen Sommer

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:

我正在尝试读取包含 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.

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

采纳答案by Brian Rogers

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.Parseinstead of JObject.Parse.

您收到此错误是因为您的 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

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

小提琴:https: //dotnetfiddle.net/2wfA17