我有这样的JSON数据:
[ {
"data": "data",
"what": "what2",
"when": 1392046352,
"id": 13,
"tags": "checkid:testcheckid, target:server.id.test, id:testid"
}, {
"data": "Test",
"what": "Test",
"when": 1395350977,
"id": 5,
"tags": "checkid:testcheckid, target:server.id.test, id:testid"
} ]
我有一个Java类,并且想将此JSON转换为我的类的实例列表。我发现了如何转换单个对象而不是列表的方法。
最佳答案
使用Jackson,您将执行以下操作:
String jsonStr = "...";
ObjectReader reader = new ObjectMapper().reader();
List<Map<String, Object>> objs = reader.readValue(jsonStr);
Map<String, Object> myFirstObj = objs.get(0);
myFirstObj.get("data");
myFirstObj.get("what");
// and so on
甚至更好的是,您可以创建一个pojo并执行以下操作:
String jsonStr = "...";
ObjectMapper mapper = new ObjectMapper();
List<MyPojo> myObjs = mapper.readValue(jsonStr, new TypeReference<List<MyPojo>>() {});
MyPojo myPojo = myObjs.get(0);
myPojo.getData();
myPojo.getWhat();
// and so on