首页 > 解决方案 > How to deserialize single JSON field with Jackson, having JSON path and DTO?

问题描述

Having JSON path String, like "foo.bar[1].baz", and corresponding DTO class in Java, how can I implement a generic method, that would deserialize single field like ObjectMapper#readValue(String,Class) would? By "corresponding DTO" I mean DTO for type that contains the path, not the type of json path object. In other words, DTO contains foo field of some type, and that type has bar list of objects with baz field. E.g.

public class MyDto {

    @JsonDeserialize(using = MyDeserializer.class)
    public LocalDate date;
    public String str;
}

public class Example {

    public static void main(String[] args){
        String json = "{\"date\":\"2021-01-01\",\"str\":\"bar\"}";
        Object deserializedPath = Example.deserialize(json, "date", MyDto.class);
    }

    public static Object deserialize(String json, String path, Class<?> dto) {
        // Here path should be deserialized with MyDeserializer(in this example), 
        // and it should work for all kinds of JSON/DTO regardless of deserializer.
    }
}

标签: javajsonjacksondtoobjectmapper

解决方案


推荐阅读