0

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!

1 Answer 1

2

You don't actually need a converter to deserialize this JSON. A simple wrapper class will do 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

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent.. thank you for you reply. nice simple solution!
No problem. Glad to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.