vb.net - Error with parsing JSON using Json.Net -
i'm using code parse json string , throws exception, error is:
an unhandled exception of type 'system.invalidcastexception' occurred in myapp.exe additional information: unable cast object of type 'newtonsoft.json.linq.jproperty' type 'newtonsoft.json.linq.jobject'.
i have imported json.net , same code works in different sub , parses fine.
here code:
dim o jobject = jobject.parse(responsecontent) dim results list(of jtoken) = o.children().tolist each item jproperty in results item.createreader() select case item.name case "response" dim batterycharge string each subitem jobject in item.values batterycharge = subitem("battery_level") messagebox.show(batterycharge) next end select next
the json string looks , need fetch battery_level
if tell me how include more if need great.
{ "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 supercharger? "battery_range": 239.02, // rated miles "est_battery_range": 155.79, // range estimated recent driving "ideal_battery_range": 275.09, // ideal miles "battery_level": 91, // integer charge percentage "battery_current": -0.6, // current flowing battery "charge_starting_range": null, "charge_starting_soc": null, "charger_voltage": 0, // has value while charging "charger_pilot_current": 40, // max current allowed charger & adapter "charger_actual_current": 0, // current being drawn "charger_power": 0, // kw (rounded down) of charger "time_to_full_charge": null, // valid while charging "charge_rate": -1.0, // float mi/hr charging or -1 if not charging "charge_port_door_open": true } }
the easiest way avoid using jobject.parse
approach , instead deserialize poco, so:
sub main dim response = jsonconvert.deserializeobject(of responseobject)("*your json string goes here*") console.writeline("the battery level " & response.response.battery_level) end sub public class response public property charging_state string public property charge_to_max_range boolean public property max_range_charge_counter integer public property fast_charger_present boolean public property battery_range double public property est_battery_range double public property ideal_battery_range double public property battery_level integer public property battery_current double public property charge_starting_range object public property charge_starting_soc object public property charger_voltage integer public property charger_pilot_current integer public property charger_actual_current integer public property charger_power integer public property time_to_full_charge object public property charge_rate double public property charge_port_door_open boolean end class public class responseobject public property response response end class
this means can access , use other properties later on in addition battery_level
.
Comments
Post a Comment