我有以下Json,我希望在vb.net中循环并提取问题和结果。我试图使用Newtonsoft.json,但我收到错误,虽然JSONlint验证了Json。实现这一目标的正确方法是什么?
{
"Vehicle_Check": [
19,
{
"question": "Brakes",
"result": "OK",
"Fault": ""
},
{
"question": "Water Levels",
"result": "OK",
"Fault": ""
},
{
"question": "Horn",
"result": "OK",
"Fault": ""
},
{
"question": "Washers",
"result": "OK",
"Fault": ""
},
{
"question": "Wipers",
"result": "OK",
"Fault": ""
},
{
"question": "Indicators",
"result": "OK",
"Fault": ""
},
{
"question": "Reflectors",
"result": "OK",
"Fault": ""
},
{
"question": "Oil Levels",
"result": "OK",
"Fault": ""
},
{
"question": "Lights",
"result": "OK",
"Fault": ""
},
{
"question": "Mirrors",
"result": "OK",
"Fault": ""
},
{
"question": "Steering",
"result": "OK",
"Fault": ""
},
{
"question": "Tyres Wheels",
"result": "OK",
"Fault": ""
},
{
"question": "Battery",
"result": "OK",
"Fault": ""
},
{
"question": "Fuel or Oil Leaks",
"result": "OK",
"Fault": ""
},
{
"question": "Other",
"result": "OK",
"Fault": ""
}
]
}
我用来解析Json的代码是:
Dim o As JObject = JObject.Parse(VCItem.Check)
Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
item.CreateReader()
Select Case item.Name
'process data here
End Select
Next
这仅返回最后一个元素:
{[
19,
{
"question": "Other",
"result": "OK",
"Fault": ""
}
]}
答案 0 :(得分:0)
实际上它正在返回第一个和最后一个元素。鉴于您发布的内容,19是数组中的第一个项目,无论如何都不合适。
尝试这个(是的,我知道它看起来很可怕)但我不得不从列表中删除19,因为它不是一个对象而是一个字符串。你的数组中有不同的类型,如果必须保留,你需要测试字符串。我正在研究一种更好的方式来自己阅读JSON,但这比我希望的时间更长。
Dim o As JObject = JObject.Parse(VCItem)
Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
item.CreateReader()
If item.Value.Type = JTokenType.Array Then
Dim results2 As List(Of JToken) = item.Value.ToList
For Each subitem As JObject In results2
Dim results3 As List(Of JToken) = subitem.Children().ToList
For Each temp2 As JProperty In results3
temp2.CreateReader()
MsgBox(temp2.Name)
MsgBox(temp2.Value)
Next
Next
End If
Next
找到一种更简单的方法来显示你的值,但仍然取决于JSON字符串的结构(在这里找到更简单的方法:How to Parse Json children in VB.NET Newtonsoft)
Dim o As JObject = JObject.Parse(VCItem)
Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
item.CreateReader()
If item.Value.Type = JTokenType.Array Then
For Each subitem As JObject In item.Values
MsgBox(subitem("question"))
MsgBox(subitem("result"))
MsgBox(subitem("Fault"))
Next
End If
Next