如何反序列化从 IoT 中心传递到事件中心的事件?

How to deserialize an Event from IoT hub which it was passed to an Event-hub?

我正在处理来自 EventHub 的消息,该 EventHubIoT Hub 相连。我会尽量解释整个过程。

我使用终端向部署在 Azure 上的 IoT 中心组件发送以下命令:

  curl --request POST \
    --url "https://${IOT_HUB}.azure-devices.net/devices/${DEVICE}/messages/events?api-version=2018-06-30" \
    --header "Accept: application/json" \
    --header "Authorization: ${SAS_TOKEN}" \
    --data "{ \"field1\" : \"12345\", \"field2\" : \"abcde\" }" \
    --verbose

当 Azure 功能接收到事件(curl -> IoT 中心 -> 事件中心 <- Azure 功能)并打印内容时:

    @FunctionName("processSensorData")
    public void processSensorData(
            @EventHubTrigger(
                    name = "demo",
                    eventHubName = "", // blank because the value is included in the connection string
                    cardinality = Cardinality.ONE,
                    connection = "EventHubConnectionString")
                    String item,
            final ExecutionContext context) {

        context.getLogger().info("Event hub message received: " + item.toString());

我在控制台中收到以下消息:

    [
    {
       "id":"xxx",
       "topic":"/SUBSCRIPTIONS/xxx/RESOURCEGROUPS/xxxPROVIDERS/MICROSOFT.DEVICES/IOTHUBS/Txxxx",
       "subject":"devices/xxx",

   "eventType":"Microsoft.Devices.DeviceTelemetry",
   "eventTime":"2020-04-13T15:02:15.253Z",
   "data":{
      "properties":{

      },
      "systemProperties":{
         "iothub-content-type":"application/x-www-form-urlencoded",
         "iothub-content-encoding":"",
         "iothub-connection-device-id":"xxx",
         "iothub-connection-auth-method":"{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}",
         "iothub-connection-auth-generation-id":"xxx",
         "iothub-enqueuedtime":"2020-04-13T15:02:15.253Z",
         "iothub-message-source":"Telemetry"
      },
      "body":"yyy"
   },
   "dataVersion":"",
   "metadataVersion":"1"
}]

但正文似乎已加密。

如何将正文解码为 return 原始请求?

"{ \"field1\" : \"12345\", \"field2\" : \"abcde\" }"

非常感谢

胡安·安东尼奥

正文采用 base64 URL 编码。您应该在代码中对其进行解码,然后将 JSON 对象解析出来。尝试使用此代码进行解码:

  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  var jsonStr = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

您应该设置系统消息属性,例如 contentTypeapplication/jsoncontentEncodingUTF-8 在你的 POST 请求中。