我正在使用此代码来解析我的JSON字符串并引发异常,错误是:
Myapp.exe中出现未处理的“System.InvalidCastException”类型异常附加信息:无法将“Newtonsoft.Json.Linq.JProperty”类型的对象强制转换为“Newtonsoft.Json.Linq.JObject”。
我已正确导入Json.Net,这个相同的代码在不同的子代码中工作并解析得很好。
这是我的代码:
Dim o As JObject = JObject.Parse(responseContent)
Dim results As List(Of JToken) = o.Children().ToList
For Each item As JProperty In results
item.CreateReader()
Select Case item.Name
Case "response"
Dim BatteryCharge As String
For Each subitem As JObject In item.Values
BatteryCharge = subitem("battery_level")
MessageBox.Show(BatteryCharge)
Next
End Select
Next
JSON字符串看起来像这样,现在我只需要获取battery_level
但是如果你能告诉我如何在我需要的时候包含更多内容那就太棒了。
{
"response": {
"charging_state": "Complete", // "Charging", ??
"charge_to_max_range": false, // current std/max-range setting
"max_range_charge_counter": 0,
"fast_charger_present": false, // connected to Supercharger?
"battery_range": 239.02, // rated miles
"est_battery_range": 155.79, // range estimated from recent driving
"ideal_battery_range": 275.09, // ideal miles
"battery_level": 91, // integer charge percentage
"battery_current": -0.6, // current flowing into battery
"charge_starting_range": null,
"charge_starting_soc": null,
"charger_voltage": 0, // only has value while charging
"charger_pilot_current": 40, // max current allowed by charger & adapter
"charger_actual_current": 0, // current actually being drawn
"charger_power": 0, // kW (rounded down) of charger
"time_to_full_charge": null, // valid only while charging
"charge_rate": -1.0, // float mi/hr charging or -1 if not charging
"charge_port_door_open": true
}
}