我收到数据:
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产品转换为String产品;和价格成双倍价格;?
答案 0 :(得分:1)
正如@Aravind所说,你可以定义一个POJO类来将数据打包为对象属性,如Payload
,并序列化&amp;使用某些json库(例如jackson
,fastjson
)将数据反序列化为POJO和json字符串之间的事件正文,或者从http://www.json.org/中选择一个最喜欢的数据。
答案 1 :(得分:0)
以下是问题的解决方案:
BankAccount
这里我从类产品中读取了一个对象中的JSON字符串,Product类包含带有getter的变量,product和price。它有效!
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;
}
}