0

I have a class that I want to be deserialized through calling a constructor with one method that accepts the full json object as String:

public class MyDataObject {

    @IwantObjectMapperToCallThisWhenDeserializing
    public MyDataObject(String json) {
      // custom logic
    }
}

Is it possible to achieve with simple annotations only, without impementing my own JsonDeserializer?

Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • Take a look at [Dynamic field type in DTO](https://stackoverflow.com/questions/55912805/dynamic-field-type-in-dto/55917767#55917767), [Cannot deserialize from Object value (no delegate- or property-based Creator) using Jackson](https://stackoverflow.com/questions/60720798/cannot-deserialize-from-object-value-no-delegate-or-property-based-creator-us/60728376#60728376). – Michał Ziober Dec 07 '20 at 11:16

1 Answers1

0

I did not find a direct way to do it, but here's a workaround:

public class MyDataObject {

    @JsonCreator(mode = Mode.DELEGATING)
    // passed object is a Map, but as long as the type is serializable below, it can by any type
    public MyDataObject(Object map) {
        String json;
        try {
            json = new ObjectMapper().writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error deserializing MyDataObject", e);
        }
        // custom logic
    }
}
Dariusz
  • 21,561
  • 9
  • 74
  • 114