- If you wanna override default deserialiser for specific properties, you can mark the properties and the deserialiser you want to use, eg:
--
// root json object
public class Example {
private String name;
private int value;
// You will implement your own deserilizer/Serializer for the field below//
@JsonSerialize(converter = AddressSerializer.class)
@JsonDeserialize(converter = AddressDeserializer.class)
private String address;
}
Here is a complete example.
- If you want to use non spring managed object mapper in Spring application context and configure the serialisers/deserialisers to use spring managed services to query the database, that can be achieved by telling Jackson to use
Spring Handler instantiator
to create instances of Deserialisers/Serialisers.
In your application context config, create ObjectMapper
bean with SpringHandlerInstantiator
eg:
@Autowired
ApplicationContext applicationContext;
@Bean
public ObjectMapper objectMapper(){
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.handlerInstantiator(handlerInstantiator());
// add additional configs, etc.. here if needed
return builder.build();
}
@Bean
public HandlerInstantiator handlerInstantiator(){
return new SpringHandlerInstantiator(applicationContext.getAutowireCapableBeanFactory());
}
Then you can @Autowire above objectMapper to deserialise jsons:
@Autowired
ObjectMapper objectMapper;
public Something readSomething(...){
...
Something st = objectMapper.readValue(json, Something.class);
...
return st;
}
Regardless of the deserialiser you want to use, ie: field or class, you can use spring context in the deserialiser, meaning that you can @Autowire your services or any spring bean managed by the same ApplicationContext
into it.
public class MyCustomDeserialiser extends ..{
@Autowired;
MyService service;
@AutoWired
SomeProperties properties;
@Override
public MyValue deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
....
}
...
}
Additionally, you can find an example of Jackson deserialiser here.