What is the best and easiest way to instantiate beans in custom way (not by calling default constructor) while deserializing from JSON using Jackson library? I found that there is JsonDeserializer
interface that I could implement, but I'm not too sure how to wire it all together into the ObjectMapper
.
UPDATE #1: I think some more details is required for my question. By default Jackson's deserializer uses default constructor to crete beans. I'd like to be able to implement instantiation of the bean by calling external factory. So what I need is just a class of the bean that needs to be instantiated. The factory will return instance that can then be provided to Jackson for property population and so on.
Please note that I'm not concerned about creation of simple/scalar values such as strings or numbers, only the beans are in the area of my interest.
Some things that may help...
First, you can use @JsonCreator to define alternate constructor to use (all arguments must be annotated with @JsonProperty because bytecode has no names), or a static factory. It would still be part of value class, but can help support immutable objects.
Second, if you want truly custom deserialization process, you can check out https://github.com/FasterXML/jackson-docs/wiki/JacksonHowToCustomSerializers which explains how to register custom deserializers.
One thing that Jackson currently misses is support for builder-style objects; there is a feature request to add support (and plan is to add support in future once developers have time).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With