SpringBoot-24 - detailed explanation of jackson configuration of default Json framework
How spring boot returns JSON data
At present, there are three JSon formats provided by SpringBoot:
-
Default jackson
-
Gson
-
JsonB
-
fastjson (this is provided by Alibaba and is now widely used in China)
We can see all these in the spring boot autoconfigure module spring boot autoconfigure
Why does springboot use Jackson by default?
This is because Jason's dependency package Jackson databind has been relied on in the spring boot starter web dependency package. Yes, Jackson has become the default Json processor of Springboot.
Now let's start to explain the detailed configuration of Jackson, the default Json framework of SpringBoot.
Detailed explanation of Jackson
Jackson default implementation
When we created the springboot project and introduced the spring boot starter web dependency, springboot began to help us with Json processing of entities.
For example, we create a Student entity class:
@Data public class Student implements Serializable{ private Long id; private String name; private String sex; private int age; private String email; private String mobile; private int isEnabled; private Date createDate; private Date updateDate; }
Then create the corresponding control layer processing class:
@Slf4j @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @GetMapping("/selectall") public List<Student> getAll() { return studentService.getAll(); } }
Note:
- @The RestController annotation will use HttpMessageConverter to convert the data and write it into the body data area of the Response.
The test results are:
Jackson configuration
In the above figure, we find that the date format is not the yyyy MM DD HH: mm: SS format we want, so how can we convert the default time format to the time format we want through Jackson?
Through the application The corresponding configuration of jackson is implemented in YML
jackson: #Date type formatting date-format: yyyy-MM-dd HH:mm:ss
After the configuration, we test again http://localhost:8899/student/selectall The interface results are as follows:
Code configuration through ObjectMapper
We will start with application The configuration annotation of the time format configured in YML is then implemented in the code using ObjectMapper
@Configuration public class MyJacksonConfig { @Bean @Primary @ConditionalOnMissingBean public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder){ ObjectMapper mapper = builder.createXmlMapper(false).build(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return mapper; } }
The results are consistent with the implementation in the configuration.
Using annotations in entity classes
Add notes to the fields to be transformed to transform the format. The implementation is as follows
@Data @JsonPropertyOrder(value={"name","mobile","sex"}) public class Student implements Serializable{ @JsonIgnore private Long id; private String mobile; @JsonProperty("Gender") private String sex; private String name; private int age; @JsonProperty("mailbox") private String email; private int isEnabled; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createDate; private Date updateDate; }
After adding comments, we test again http://localhost:8899/student/selectall The interface results are as follows:
In the figure, we find that the name and mobile fields have changed in order, sex has not only changed in order, but also used aliases, and the id field has disappeared, which is the function of jackson annotation.
Common Jackson notes:
-
**@JsonPropertyOrder(value = {"value1", "value2", "value3"}) * *: convert the entity correspondence to the default json order, and transform it according to the annotation requirements
-
@JsonIgnore: exclude a field from serialization and deserialization
-
**@JsonFormat(pattern = "yyyy MM DD HH: mm: SS", timezone = "GMT+8") * *: convert according to the specified date format
-
**@JsonProperty("mailbox") * *: alias the corresponding field
-
**@JsonInclude(JsonInclude.Include.NON_NULL) * *: if the field is empty, serialization and deserialization will not be performed
Jackson common configuration
# Standard name or class name format, date only util. Serialization format of date spring.jackson.date-format= yyyy-MM-dd HH:mm:ss # Specify the format of Joda date/time, such as yyyy mm ddhh: mm: SS If not configured, dateformat will be used as backup. spring.jackson.joda-date-time-format= yyyy-MM-dd HH:mm:ss # Globally set the serialization method of pojo or attributes annotated by @ JsonInclude spring.jackson.default-property-inclusion= NON_NULL # Attributes that are not empty will be serialized. See jsoninclude for specific attributes Include # Whether to enable Jackson's serialization # Example: spring jackson. serialization. indent-output= true spring.jackson.serialization.*= # Enable deserialization of Jackson spring.jackson.deserialization.*= # Whether to enable json generators # Example: spring jackson. generator. auto-close-json-content=true spring.jackson.generator.*= # Specifies the Locale used by json spring.jackson.locale= zh # Do you want to turn on Jackson's general features spring.jackson.mapper.*= # Whether to enable the parser feature of jackson spring.jackson.parser.*= # Specify Json policy mode spring.jackson.property-naming-strategy=com.fasterxml.jackson.databind.PropertyNamingStrategy.UpperCamelCaseStrategy # or spring.jackson.property-naming-strategy=UPPER_CAMEL_CASE # Enable deserialization of Jackson spring.jackson.serialization.*= # Specify the date and format the time zone, such as America/Los_Angeles or GMT+10 spring.jackson.time-zone= GMT+8
Note:
- These configurations can also be implemented through ObjectMapper
If you think this article is good, you are welcome to pay attention, like and collect support. Your attention is the driving force of my persistence!
Official account springboot sunflower collection mainly shares JAVA technology, reply: springboot get springboot related code video data
Original is not easy, reprint please indicate the source, thank you for your support! If this article is useful to you, welcome to forward and share!