SpringBoot Json resolution scheme in custom configurations and methods (a) - using Jackson

First, understandingHttpMessageConverter

HttpMessageConverter (message conversion tool):
 All raw JSON Chengdu without it, SpringMVC automatically configured Jacksonand Gsonare HttpMessageConverter, therefore users Jacksonand Gsonif you no additional configuration, you only need to add a dependency can be.
 Spring MVC using HttpMessageConverterinterface conversion HTTP requests and responses. Sensible default settings are contained in 开箱即用the. I mean, if you configure Jacksonand Gsonthen use your system default, if you do not have to configure, use the system-supplied! This is the mainstream thinking of Spring: SpringBoot agreement is greater than the configuration

1.API return the results and how to parse json format data into Java objects returned to the front end, is about to end service object returned serialized as JSON characters
2. front end of the incoming json how the data is parsed into Java objects as parameters into the API, will soon front end came the JSON string deserialized into Java objects

Second, view the source code

 Create a simple Spring project, import the Web dependence, reliance can be found which contains the json dependent, so no additional add any dependencies.
Here Insert Picture Description

  • JSON:
    Location: org/springframework/boot/autoconfigure/http/JacksonHttpMessageConvertersConfiguration.java
    (for Gson is completely consistent, but the use of Gson needs to be added dependent on the respective Gson;)
@Configuration(proxyBeanMethods = false)
class JacksonHttpMessageConvertersConfiguration {

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(ObjectMapper.class)
	@ConditionalOnBean(ObjectMapper.class)
	@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
			havingValue = "jackson", matchIfMissing = true)
	static class MappingJackson2HttpMessageConverterConfiguration {

		@Bean
		@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class,
				ignoredType = {
						"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
						"org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })
		MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
			return new MappingJackson2HttpMessageConverter(objectMapper);
		}

	}

@ConditionalOnClass(ObjectMapper.class): If you import json dependent, the system will default to the above configuration, use MappingJackson2HttpMessageConverterconversion tools, to take effect.
@ConditionalOnMissingBean: If there is no Bean configuration, the system will default to the Bean here, if you have a need for additional time format, etc., need self-configuration, the system will be user-configured precedence Bean Bean and ignore system configuration

Third, custom configuration

Controller class to write a simple, simple test

@RestController
@RequestMapping("/test")
public class StudentController {
    @GetMapping("/hello")
    public Student get(){
        Student student = new Student();
        student.setId((long) 1);
        student.setAge(15);
        student.setName("alvin");
        student.setBirthday(new Date());
        return student;
    }
}

Postman call interface
Here Insert Picture Description
entity class corresponding map field together with @JsonFormat(pattern = "yyyy-MM-dd")annotation format modified

public class Student {
    private Long id;
    private String name;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday
}

Here Insert Picture Description
 In this manner a simple operation, but not very practical, if the project contains a plurality of entity classes, and each class containing a plurality of entity to add a Date property, in this way will be very tedious and error prone!
Thus, the overall configuration is more convenient to use, is to use JacksonHttpMessageConvertersConfiguration.javathe action, the user can independently configure the format conversion json

Configuration:

Option One:

 Create a new JsonConfig.javaa configuration class (remember to test before @JsonFormat(pattern = "yyyy-MM-dd")annotation commented out)

@Configuration
public class JsonConfig {
    @Bean
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        //更改日期全局配置
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy/MM/dd"));
        converter.setObjectMapper(objectMapper);
        return converter;
    }
}

 The Bean will replace JacksonHttpMessageConvertersConfiguration.javathe bean, as @ConditionalOnMissingBeanhas been satisfied, the system default configuration automatically expire.

  • postman calls, the date format generated
    Here Insert Picture Description
    objecMapper following a lot of other configurations can also be used in this way:
    Here Insert Picture Description

Option II:

 Through a scheme can be found, modify the format operation is mainly to objecMapperoperate, MappingJackson2HttpMessageConvertersimply to provide an object does not actually do anything to our operating format, so we can provide alone ObjectMapper
 in JacksonHttpMessageConvertersConfiguration.java appear @ConditionalOnClass ( ObjectMapper.class), which Objectmapper is coming from a different injection configuration, namely JacksonAutoConfiguration.java
position: org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java
 of course, what we debug verify them here, indeed program after here!
Here Insert Picture Description
 Therefore, we can individually JsonConfig.javaconfigure ObjectMapper can!

    @Bean
    ObjectMapper objectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy/MM/dd"));
        return objectMapper;
    }

Debug and found the program to go @Bean user self-configuration, the system automatically ignores @Bean automatic configuration
Here Insert Picture Description
is still in force:
Here Insert Picture Description

Published 71 original articles · won praise 102 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_44717317/article/details/104441519