如何处理从 Azure IoT 中心接收到的数据

How can I work with the received DATA from 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());
    }
}

这里我成为产品名称和价格:

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

如何将Payload, product 转化为String product;并且价格变成双倍价格;?

正如@Aravind 所说,您可以定义一个 POJO class 将数据打包为对象属性,如 Payload,并将数据序列化和反序列化为 POJO 和 [= 之间的事件主体17=] 字符串使用一些 json 库,例如 jackson, fastjson, or choose a favorite one from http://www.json.org/.

小飞侠和Aravind帮我解决了问题。

问题的解决方法如下:

public class Product {
public Product(){

}
    private String product;
    private Double price;

public Product(String json ){
    Gson gson=new Gson();
    try{
        Product product =gson.fromJson(json, Product.class);
        if (product!=null){
            System.out.println("Name: " +product.getProduct());
        }
    }catch (Exception e){
        System.out.println("failed: " +e.getMessage());
    }
}

    public String getProduct() {
        return product;
    }

    public Double getPrice() {
        return price;
    }
 }

在这里,我将 JSON 字符串从 Class 产品读取到对象中,产品 class 包含变量、产品和价格 getter。有效!

    public Product(String json ){
    Gson gson=new Gson();
    try{
        Product product =gson.fromJson(json, Product.class);
        if (product!=null){
            System.out.println("Name: " +product.getProduct());
        }
    }catch (Exception e){
        System.out.println("failed: " +e.getMessage());
    }
}