springboot-How to do custom JSON serialization in SpringBoot(RESTful) apps
This post would demo how to do custom JSON serialization in SpringBoot apps(Spring MVC or RESTful service). By default, SpringBoot uses jackson to serialize objects. For example:
If we have this object:
And the above object is returned by a SpringBoot Restful service like this:
We run the SpringBoot app and visit http://localhost:8080/myBean, then we would get this result:
The bornDate field is a Long literal, what if we want it to be in format MM-dd-yyyy HH:mm:ss,just like this:
How to do this job?
- SpringBoot 1.x and 2.x
3. Ways to do this job
3.1 use @JsonFormat
You can just use the @JsonFormat to specify the pattern of the field to do custom serialization, just as follows:
3.2 use custom JsonSerializer
the @JsonFormat can only change the field with this annotation, if you want to permernantly change the serialization of some type, you can just define a custom JsonSerializer.
First define a custom JsonSerializer by extending the JsonSerializer:
Then ,add this custom serializer to ObjectMapper:
4. The @JsonSerialize(using = CustomDateSerializer.class) problem
If we use the @JsonSerialize(using = CustomDateSerializer.class), we would get this error:
It seems that this annotation is not supported by SpringBoot anymore, just be careful.
The example source code has been uploaded to github, you can visit here to view the example source codes.