有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java jackson从映射中获取列表,其中键包含路径(如“child\u 1\u name”)

我们的集成点返回给我们以下结构

{
  "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) 个答案

  1. # 1 楼答案

    可以通过扩展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());
    }