1

I am trying to make a message handler for received JSON strings over MQTT. I have this working for one type of message.

Here is my code:

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
   // handle message received
   Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
   string source = Encoding.UTF8.GetString(e.Message);
   dynamic data = JObject.Parse(source);
  
  Console.WriteLine(data.content.value); 
  // this data.content.value is working for message 1 but crashes for message 2
}

How can I avoid using a lot of try catches in my message handler in case I have 2 (or more) different MQTT messages entering?

These are my 2 types of messages for now:

/// message 1:
{
    "header": {
        "headeritem": "exampleheader",
        "type": "headertype",
        "info": "headerinfo"
    },
    "content": {
        "name": "contentname",
        "value": true
    }
}

/// message 2:
{
    "header": {
        "headeritem": "exampleheader",
        "type": "headertype",
        "info": "headerinfo"
    },
    "content": {
        "item1": "exampleitem1",
        "item2": "exampleitem2",
        "item3": [
          {
            "item3type1": "exampletype1.1",
            "item3type2": "exampletype2.1",
            "item3type3": "exampletype3.1",
            "item3type4": ["0xFFAA"]
          },
          {
            "item3type1": "exampletype1.2",
            "item3type2": "exampletype2.2",
            "item3type3": "exampletype3.2",
            "item3type4": ["0xFFBB"]
          },
          {
            "item3type1": "exampletype1.3",
            "item3type2": "exampletype2.3",
            "item3type3": "exampletype3.3",
            "item3type4": ["0xFFCC"]
          }
        ]
    }
}
Vincent
  • 2,073
  • 1
  • 17
  • 24
Koenieboy
  • 23
  • 1
  • 6

1 Answers1

1

When you do not know what JSON type is comming in, you can use reflection on the dynamic data type to check if the property exists.

Like explained here: Test if a property is available on a dynamic variable

However, when the different JSON formats are limited to only a few, maybe you are better off creating hard typed classes to parse the JSON in.

Like explained here: How to Convert JSON object to Custom C# object?

This way you do not have to worry about whether a property exists.

Vincent
  • 2,073
  • 1
  • 17
  • 24
  • Thx, seems to work like a charm now using hard typed class. First i struggled a bit because i was creating 2 classes for my 2 messages, but now i combine them in one and this works perfect! I used [link](https://quicktype.io/csharp/) to create the classes. – Koenieboy Jan 21 '21 at 08:12