我对Newtonsoft.Json有问题。 我正在尝试从 URL 解析 JSON,但收到错误。 这是 JSON:
[
{
"ID": "0",
"Nome": "we",
"Data": "2013-09-16",
"Orario": "00:00:16",
"Prestazione": "dfg",
"Stato": "dfg",
"Numero_Telefono": "dfg"
},
{
"ID": "0",
"Nome": "fg",
"Data": "2013-09-26",
"Orario": "00:00:00",
"Prestazione": "",
"Stato": "",
"Numero_Telefono": ""
},
{
"ID": "1",
"Nome": "davide",
"Data": "2013-09-26",
"Orario": "00:00:16",
"Prestazione": "ds",
"Stato": "sd",
"Numero_Telefono": "3546"
}
]
这是我正在使用的代码:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://nhd.altervista.org/connectDb.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JObject = JObject.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JProperty In results
item.CreateReader()
MsgBox(item.Value("img")) ' because my tag in json is img
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try
这是我尝试解析 JSON 时收到的错误:
Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
你能帮我解决这个问题吗?
您收到此错误是因为您使用的是 JObject.Parse
,它需要一个 JSON 对象,但您的 JSON 包含一个数组。 若要更正此问题,请改用JArray.Parse
。
但是,还有另一个问题:代码的其余部分没有设置为正确处理结果。 由于结果是对象数组,因此For Each
循环需要期望JObject
项,而不是JProperty
项。 拥有每个项目后,您可以根据需要从中获取属性。
我不确定您尝试对item.CreateReader()
行做什么,因为您没有对其返回值执行任何操作,而且您似乎不需要。 同样,我也对你的MsgBox(item.Value("img"))
行感到困惑,因为 JSON 中的任何地方都没有"img"属性。 因此,这将始终为空。
下面是一些更正的代码,它将解析 JSON 并在结果中显示每个对象的所有属性。 这应该为您提供一个起点。
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Try
request = DirectCast(WebRequest.Create("http://nhd.altervista.org/connectDb.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
Dim jResults As JArray = JArray.Parse(rawresp)
Dim results As List(Of JToken) = jResults.Children().ToList()
For Each item As JObject In results
Dim demo As String = ""
For Each prop As JProperty In item.Properties()
demo = demo + prop.Name + " = " + prop.Value.ToString() + vbCrLf
Next
MsgBox(demo)
Next
Catch ex As Exception
Console.WriteLine(ex.ToString)
MsgBox(ex.ToString)
Finally
If Not response Is Nothing Then response.Close()
End Try