【发布时间】:2021-04-25 05:32:27
【问题描述】:
我正在尝试为通过 MQTT 接收的 JSON 字符串创建一个消息处理程序。我有这个适用于一种类型的消息。
这是我的代码:
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
}
如果我输入了 2 个(或更多)不同的 MQTT 消息,如何避免在消息处理程序中使用大量 try catch?
这是我目前的两种消息:
/// 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"]
}
]
}
}
【问题讨论】: