0

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.
    }
}
  • There's a library for that: https://github.com/json-path/JsonPath – Benjamin M Mar 05 '21 at 23:31
  • Yes, using JsonPath I can deserialize specific path into object of desired type, but that is not what I need. I basically don't know the target type of json path, I only know the type of whole json. The basic algorithm is: 1 - get Jackson deserializer for java field that corresponds to json path, deserialize into that type. – Dmitry Minaev Mar 06 '21 at 15:44
  • Maybe you should share a [mcve]? But in general, json doesn't carry type information unless you're using JsonSchema – OneCricketeer Mar 06 '21 at 16:14
  • Added a code example – Dmitry Minaev Mar 06 '21 at 19:04

0 Answers0