Spring Boot - Custom JSON Serialization
Solution 1
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:
You can configure a custom serializer by using Jackson2ObjectMapperBuilder.
Solution 2
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`.
Punter Vicky
Updated on July 21, 2022Comments
-
Punter Vicky almost 2 years
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 ?
-
Punter Vicky over 7 yearsThanks @dimuha. But I have multiple date fields each having different format.
-
Punter Vicky over 7 yearsThanks @Lakatos. I updated the mixins but still doesn't take effect. I have updated the code in my original post.
-
Punter Vicky over 7 yearsI implemented this in a separate program and this works great. However when I used it in my app , it didn't return the formatted date. I am extending classes from few jars which are using EnableMvc annotation. I am suspecting this causing serialization from being performed.