如何将动态JSON属性映射到固定的POJO字段 [英] How to map a dynamic JSON property to a fixed POJO field

查看:118
本文介绍了如何将动态JSON属性映射到固定的POJO字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些json我要解析为pojo

I have some json that i want to parse into pojo

{
  "groups": [
    {
      "g1": [
        1,2,5,6,7
      ]
    },
    {
      "g2": [
        2,3,48,79
      ]
    }
  ]
}   

当然,g1g1是标识符,所以我想象的那样pojos会像......

Of course, "g1" and "g1" are the identifiers, so what i would imagine as pojos would be sth like

class Container {
    List<Group> groups;
}

class Group {
    String id;
    List<Integer> values;
}

所以归结为这个问题:如何使用jackson来映射json -poperty to the pojo?

So it boils down to this question: How to use jackson to map a json-property to the pojo?

推荐答案

可以使用添加了JsonDeserialize注释的自定义反序列化器来解析这种结构。

This kind of structure can be parsed using a custom deserializer added with the JsonDeserialize annotation.

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 ...

Deserializer, note use of ObjectMapper.readTree rather than using the low level 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]]]]

这篇关于如何将动态JSON属性映射到固定的POJO字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆