2016-06-25 51 views
1

接收到的數據工作,我接收到的數據:怎樣才能從Azure的物聯網中心

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

我如何可以採取的有效載荷,產品轉換爲String產品;並將價格轉化爲雙重價格;?

+0

有效載荷將是一個json字符串。所以你可以反序列化到適當的對象並使用.. – Aravind

回答

0

Peter Pan和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字符串中到從類產品的目的,產品類包含的變量,產品價格UND吸氣劑。有用!

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

正如@Aravind所述,可以定義一個POJO類打包該數據作爲像Payload對象屬性和序列&反序列化數據作爲POJO和使用一些JSON庫JSON字符串之間的事件體,如jacksonfastjson,或從http://www.json.org/中選擇一個最喜歡的。