c# - Access nested key value pairs -
i have relatively simple nested json string data below:
{ "d" : { "humidity": "39.21", "acc_y": "1.21", "ambient_temp": "24.21", "air_pressure": "1029.21", "object_temp": "23.21", "acc_z": "0.21", "acc_x": "3.21", } } i have c# windows service application receives json string , deserialize string.
private static void client_mqttmsgpublishreceived(object sender, uplibrary.networking.m2mqtt.messages.mqttmsgpublisheventargs e) { //console.writeline(system.text.encoding.default.getstring(e.message)); string json = system.text.encoding.default.getstring(e.message); var obj = jsonconvert.deserializeobject<idictionary<string, object>>(json, new jsonconverter[] { new myconverter() }); } i have myconvert class looks this, reads json:
class myconverter : customcreationconverter<idictionary<string, object>> { public override idictionary<string, object> create(type objecttype) { return new dictionary<string, object>(); } public override bool canconvert(type objecttype) { // in addition handling idictionary<string, object> // want handle deserialization of dict value // of type object return objecttype == typeof(object) || base.canconvert(objecttype); } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { if (reader.tokentype == jsontoken.startobject || reader.tokentype == jsontoken.null) return base.readjson(reader, objecttype, existingvalue, serializer); // if next token not object // fall on standard deserializer (strings, numbers etc.) return serializer.deserialize(reader); } } i can see json data in debug window in obj object.
this may straight forward question, how extract json key value pair data (eg. humidity, ambient temp) use in program, can see them in debug window?
thank help!
you don't need converter deserialize json. simple wrapper class it:
class wrapper { public dictionary<string, object> d { get; set; } } then:
dictionary<string, object> obj = jsonconvert.deserializeobject<wrapper>(json).d; fiddle: https://dotnetfiddle.net/vnoqxi
Comments
Post a Comment