杰克逊从地图上获取列表,其中键包含路径(例如“ child_1_name”)

时间:2019-01-30 17:50:06

标签: java jackson2

我们的整合点返回给我们以下结构

{
  "veryImportantProperty":"some value",
  "child_1_name": "Name1",
  "child_1_age": 15,
  "child_2_name": "Name2",
  "child_2_age": 18
}

我们想将其解析为以下类:

class Child {
  @NotEmpty
  private String name;
  @NotNull
  private Integer age;
}

class Wrapper{
  @NotEmpty
  private String veryImportantProperty;
  @Valid
  private List<Child> children;
}

Jackson是否有任何插件/配置可以帮助我?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以通过扩展StdDeserializer来定义自定义Deserializer

class WrapperDeserializer extends StdDeserializer<Wrapper> {

    public WrapperDeserializer() {
        this(null);
    }

    public WrapperDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Wrapper deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);


        String veryImportantProperty = node.get("veryImportantProperty").asText();
        List<Child> children = new ArrayList<Child>();
        int iChild = 1;
        Child child;
        while(node.has("child_"+iChild+"_name")) {
            child = new Child();
            child.setName(node.get("child_"+iChild+"_name").asText());
            child.setAge(node.get("child_"+iChild+"_age").asInt());
            children.add(child);
            iChild++;
        }

        Wrapper wrapper = new Wrapper();
        wrapper.setVeryImportantProperty(veryImportantProperty);
        wrapper.setChildren(children);
        return wrapper;
    }
}

然后用@JsonDeserialize注释您的Wrapper类,以使用自定义的反序列化器

@JsonDeserialize(using = WrapperDeserializer.class)
class Wrapper {
    ...
}

然后,您可以使用ObjectMapper.readValue方法在一行中反序列化

ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = null;
try {
    wrapper = mapper.readValue(json, Wrapper.class);
} catch (Exception e) {
    System.out.println("Something went wrong:" + e.getMessage());
}