问题
I receive the Data:
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());
}
}
Here i become the product name and price:
System.out.println(String.format("| Message Payload: %s", new String(receivedEvent.getBody(), Charset.defaultCharset())));
How can i take the Payload, product into a String product; and the price into double price;?
回答1:
As @Aravind said, you can define a POJO class to package the data as object properties like Payload
, and serialize & deserialize the data as event body between a POJO and a json string using some json library, such as jackson, fastjson, or choose a favorite one from http://www.json.org/.
回答2:
Peter Pan and Aravind helped me to solve the Problem.
Here is the solution for the problem:
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;
}
}
Here i read the JSON String in into a Object from the Class Product, the Product class contains variables, product und price with getter. It works!
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());
}
}
来源:https://stackoverflow.com/questions/38028130/how-can-i-work-with-the-received-data-from-azure-iot-hub