我有一些json,我想解析为pojo
{
"groups": [
{
"g1": [
1,2,5,6,7
]
},
{
"g2": [
2,3,48,79
]
}
]
}
当然,"g1"
和"g1"
是标识符,所以我想象pojos会像......
class Container {
List<Group> groups;
}
class Group {
String id;
List<Integer> values;
}
所以归结为这个问题:如何使用jackson将json属性映射到pojo?
答案 0 :(得分:2)
可以使用添加了JsonDeserialize注释的自定义反序列化器来解析这种结构。
的POJO
public static class Container {
private List<Group> groups;
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
@Override
public String toString() {
return String.format("Container [groups=%s]", groups);
}
}
@JsonDeserialize(using=CustomDeserializer.class)
public static class Group {
String id;
List<Integer> values;
@Override
public String toString() {
return String.format("Group [id=%s, values=%s]", id, values);
}
}
反序列化器,注意使用ObjectMapper.readTree而不是使用低级JsonParser API ......
public static class CustomDeserializer extends JsonDeserializer<Group> {
@Override
public Group deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
Group group = new Group();
ObjectNode objectNode = new ObjectMapper().readTree(jp);
// assume only a single field...
Entry<String, JsonNode> field = objectNode.fields().next();
group.id = field.getKey();
// there might be a nicer way to do this...
group.values = new ArrayList<Integer>();
for (JsonNode node : ((ArrayNode)field.getValue())) {
group.values.add(node.asInt());
}
return group;
}
}
测试
public static void main(String[] args) throws Exception {
String json = "{\"groups\": [{\"g1\":[1,2,5,6,7]},{\"g2\": [2,3,48,79]}]}";
JsonFactory f = new JsonFactory();
JsonParser jp = f.createParser(json);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(jp, Container.class));
}
输出
Container [groups=[Group [id=g1, values=[1, 2, 5, 6, 7]], Group [id=g2, values=[2, 3, 48, 79]]]]