您的 JSON 表示简单的地图列表,更准确地说:List<Map<String, List<String>>>
. 您可以将此 JSON 转换为此 POJO:
class JsonEntity {
public List<Map<String, List<String>>> list;
public String kind;
public StuffList toStuffList() {
StuffList stuffList = createStuffListObject();
return stuffList;
}
private StuffList createStuffListObject() {
StuffList stuffList = new StuffList();
stuffList.kind = kind;
stuffList.list = createItemsList();
return stuffList;
}
private List<Stuff> createItemsList() {
List<Stuff> items = new ArrayList<Stuff>(list.size());
for (Map<String, List<String>> item : list) {
items.add(convertToStuff(item));
}
return items;
}
private Stuff convertToStuff(Map<String, List<String>> item) {
Stuff stuff = new Stuff();
stuff.name = item.keySet().iterator().next();
stuff.items = item.values().iterator().next();
return stuff;
}
}
现在我们可以用这种方式反序列化 JSON:
public static void main(String[] args) throws Exception {
String json = "{\"list\":[{\"monday\":[\"apple\", \"bread\"]},{\"sunday\":[\"bacon\", \"beer\"]} ],\"kind\":\"shoplist\"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonEntity jsonEntity = objectMapper.readValue(json, JsonEntity.class);
System.out.println(jsonEntity.toStuffList());
}
程序的输出:
list=[[name=monday, items=[apple, bread]], [name=sunday, items=[bacon, beer]]], kind=shoplist