I generally use mixins to perform custom serialization and deserialization when using Jackson Library. My RestController in Spring Boot app has methods similar to one listed below. I guess Spring Boot uses Jackson to serialize the VerifyAccountResponse into string. However this converts my calendar / date objects into a long value when they are converted to String. I am able to convert them into appropriate format by using custom serializer. However I am having to change the return type into an object after serialization. Is there a way to retain the same signature and add custom serializer to default serialization performed by Spring Boot.
@RequestMapping(value ="verifyAccount", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<VerifyAccountResponse> verifyAccount(@RequestBody VerifyAccountRequest request) {
VerifyAccountResponse response = service.verifyAccount(request);
return new ResponseEntity<VerifyAccountResponse>(response, HttpStatus.OK);
}
EDIT:
Updated the below based on the answers , but mixin doesn't seem to take effect -
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.mixIn(ConnectStatus.class, com.datacast.service.util.DateFormatSerializerMixin.class);
return builder;
}
EDIT 2:
I created a simple spring boot project to test this out and this works fine. But when I use this approach in my larger project , the date conversion is not happening. Could there be anything overriding Jackson2ObjectMapperBuilder ?
You can customize the Jackson serializer in a spring boot application in a lot of ways. Please consider checking the documentation regarding jackson in the spring boot reference guide:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/html/howto.html#howto-customize-the-jackson-objectmapper
You can configure a custom serializer by using Jackson2ObjectMapperBuilder.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.html#serializerByType-java.lang.Class-com.fasterxml.jackson.databind.JsonSerializer-
You can customize date format (as I understand it's the main reason of your post) by setting property
spring.jackson.date-format=
# Date format string or a fully-qualified date format class name.
For instance `yyyy-MM-dd HH:mm:ss`.
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