java - 使用 Java 访问 IoT 中心 Azure 中的数据

标签 java azure cloud iot azure-iot-hub

我将数据发送到物联网中心并接收它,它可以工作,但我不知道如何处理接收到的数据:这是我接收数据的代码:

public void accept(PartitionReceiver receiver)
            {
                System.out.println("** Created receiver on partition " + partitionId);
                try {
                    while (true) {
                        Iterable<EventData> receivedEvents = receiver.receive(10).get();
                        int batchSize = 0;
                        if (receivedEvents != null)
                        {
                            for(EventData receivedEvent: receivedEvents)
                            {                                    
                                System.out.println(String.format("| Time: %s", receivedEvent.getSystemProperties().getEnqueuedTime()));
                                System.out.println(String.format("| Device ID: %s", receivedEvent.getProperties().get("iothub-connection-device-id")));
                                System.out.println(String.format("| Message Payload: %s", new String(receivedEvent.getBody(), Charset.defaultCharset())));
                                batchSize++;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    System.out.println("Failed to receive messages: " + e.getMessage());
                }
            }

我想处理接收到的数据,这里我将数据变为 JSON 字符串:

System.out.println(String.format("| Message Payload: %s", new String(receivedEvent.getBody(), Charset.defaultCharset())));

数据输出为:产品:xy,价格:2.3。 我想将数据带到:

String product= product;
double price= price;

如何将收到的 Payload 保存在变量中?

谢谢

最佳答案

有两种消息,包括设备到云云到设备

对于第一种,设备到云消息,正如@DominicBetts所说,您可以引用Receive device-to-cloud messages部分了解如何使用事件中心兼容终结点接收 d2c 消息。 GitHub 上有两个示例可供引用,请参见下文。

  1. Simple send/receive sample :展示如何连接 IoT 中心,然后向 IoT 中心发送消息以及从 IoT 中心接收消息,并将您选择的协议(protocol)作为参数传递。
  2. Simple sample handling messages received : : 展示如何连接到 IoT 中心并管理从 IoT 中心收到的消息,并将您选择的协议(protocol)作为参数传递。

对于第二种,云到设备消息,您可以引用Receiving messages on the simulated device部分。了解如何接收c2d消息。文章中的示例代码是为 C# 编写的,但我认为使用 Java 而不是 C# 会更简单,请注意选择合适协议(protocol)部分中的注释。

关于java - 使用 Java 访问 IoT 中心 Azure 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37926382/

相关文章:

java - Guice 和 Wicket : using SessionScoped injections

java - Java 中的 printStackTrace() 方法有什么用?

Powershell 导入 Azure 发布设置无效的 XML

azure - 如何使用azure服务主体进行 Multi-Tenancy 应用程序?

cloud - 为什么人们选择 SnapLogic 而不是 informatica 进行云集成?

java - 即使在我的 MAC 上安装了 JRE 8 -"No Java Runtime present,requesting to install "也会显示在终端中

java - 回收站 View 不显示 Youtube 视频

azure - 事件中心——消费者横向扩展时如何防止重复处理

azure - worker 角色在 csrun.exe 中失败,但直接从 VS 运行时工作正常(VS 中的 F5)

windows - 我如何知道为什么我的 Azure 实例无法启动?