1

我收到数据:

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())));

我如何将有效负载产品转换为字符串产品;并且价格变成双倍价格;?

4

2 回答 2

1

正如@Aravind 所说,您可以定义一个 POJO 类来将数据打包为对象属性,例如Payload,并使用一些 json 库(例如jackson,, )将数据序列化和反序列化为 POJO 和 json 字符串之间的事件体fastjson,或者选择喜欢的来自http://www.json.org/

于 2016-06-27T06:31:16.300 回答
0

彼得潘和阿拉文德帮助我解决了这个问题。

这是该问题的解决方案:

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;
    }
 }

在这里,我从 Product 类中将 JSON 字符串读入一个对象,Product 类包含变量、产品和价格以及 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());
    }
}
于 2016-06-27T15:57:40.023 回答