I have a relatively simple nested JSON string for 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 a c# windows service application which receives the JSON string and 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 a Myconvert Class which looks like this, which reads the 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 to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is 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 the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}
I can see the JSON data in my debug window in the obj object.
This may be a very straight forward question, how do i extract the JSON key value pair data (eg. humidity, ambient temp) to use in my program, as currently i can only see them in the debug window?
Thank you for any help!