2015-05-06 58 views
0

我有這樣如何忽略包裝元素時解析JSON到DTO

{ 
"135": { 
    "id": "135", 
    "name": "My Awesome Washing Machine!", 
    "powerswitch": { 
    "available": "true", 
    "state": "on", 
    "reachable": "true", 
    "locked": "false" 
    }, 
    "reference": { 
    "id": "4", 
    "name": "Lave-linge", 
    "category_id":"2" 
} 
}, 
"491": { 
    "id": "491", 
    "name": "My Fridge", 
    "powerswitch": { 
    "available": "true", 
    "state": "on", 
    "reachable": "false", 
    "locked": "false" 
    }, 
    "reference": { 
    "id": "1", 
    "name": "Réfrigérateur", 
    "category_id":"1" 
    } 
} 
} 

這裏一個JSON是我的DTO:

public class Device { 
    private String id; 
    private String name; 
    private DevicePowerswitch powerswitch; 
    private DeviceReference reference; 
    //getter, setter 
} 

的問題是我怎麼能解析JSON到列表的設備。 請注意,在上面的json中有一個非靜態的id值包裝器。

回答

0

您需要將JSON解析爲JsonNode,然後迭代子節點。然後可以使用ObjectMapper將設備實例映射出您作爲結果提取出的節點。

ObjectMapper mapper = new ObjectMapper(); 
final JsonNode jsonNode = mapper.readTree(JSON); 
for (JsonNode node : jsonNode) 
{ 
    final Device device = mapper.convertValue(node, 
               Device.class); 
    // do something with the device 
} 
+0

是的,這是我需要的。謝謝 –

+0

@Lep請接受答案,如果它是正確的;這有助於他人找到答案。 –