【问题标题】:JSON message handler in C#C# 中的 JSON 消息处理程序
【发布时间】: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"]
          }
        ]
    }
}

【问题讨论】:

    标签: c# json mqtt


    【解决方案1】:

    当你不知道传入的是什么JSON类型时,可以对动态数据类型使用反射来检查属性是否存在。

    就像这里解释的那样: Test if a property is available on a dynamic variable

    但是,当不同的 JSON 格式仅限于几种时,也许您最好创建硬类型类来解析 JSON。

    就像这里解释的那样: How to Convert JSON object to Custom C# object?

    这样您就不必担心属性是否存在。

    【讨论】:

    • Thx,现在使用硬类型类似乎就像一个魅力。首先我有点挣扎,因为我正在为我的 2 条消息创建 2 个类,但现在我将它们组合在一起,这很完美!我使用link 创建类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多