我将数据发送到物联网中心并接收它,它可以工作,但我不知道如何处理接收到的数据:这是我接收数据的代码:
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 上有两个示例可供引用,请参见下文。
- Simple send/receive sample :展示如何连接 IoT 中心,然后向 IoT 中心发送消息以及从 IoT 中心接收消息,并将您选择的协议(protocol)作为参数传递。
- 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/