1

I would like to deserialize an immutable class which is defined in a dependency, and therefore I cannot modify. It only has a private constructor, and has to be built using a builder.

With Jackson it's possible to use @JsonDeserialize(builder = SomeClass.SomeClassBuilder.class) to deserialize such an object. Unfortunately, I cannot add the annotation.

Is it possible to register such a builder without using annotations, and if it is, how would you go about and do it?

Ynv
  • 1,824
  • 3
  • 20
  • 29

1 Answers1

1

You might want to have a look at the examples here (first hit on google BTW):

Define a custom Deserializer:

public class SomeClassDeserializer extends StdDeserializer<SomeClass> { 
 
    public SomeClassDeserializer() { 
        this(null); 
    } 
 
    public SomeClassDeserializer(Class<?> vc) { 
        super(vc); 
    }
 
    @Override
    public SomeClass deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        // read values from node and use the SomeClassBuilder
        // to create an instance of SomeClass
    }
}

Make Jackson aware of the deserializer by registering it with an ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(SomeClass.class, new SomeClassDeserializer());
mapper.registerModule(module);
 
SomeClass readValue = mapper.readValue(json, SomeClass.class);

Depending on the framework you're using there might be other more elegant ways to register the deserializer.

dpr
  • 10,591
  • 3
  • 41
  • 71
  • Thanks. I was wondering whether it's possible to do without a custom deserialzer? – Ynv Aug 11 '20 at 08:25
  • I doubt this is possible. You would probably need to add some annotation on the builder as well to make Jackson know what to do with it. https://stackoverflow.com/questions/4982340/jackson-builder-pattern – dpr Aug 11 '20 at 08:30
  • @Ynv Pretty much options are using the annotation or extend `JsonDeserializer`, this is how jackon will be notified you plan to use custom deserialisation. – Traycho Ivanov Aug 11 '20 at 10:50