Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate beans in custom way with Jackson?

Tags:

java

json

jackson

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.

like image 280
Tomasz Błachowicz Avatar asked Apr 18 '11 08:04

Tomasz Błachowicz


1 Answers

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).

like image 145
StaxMan Avatar answered Oct 14 '22 11:10

StaxMan