SpringBoot中jackson的两种配置方式
通过application.yml
配置属性说明:
spring.jackson.date-format:指定日期格式,比如yyyy-MM-dd HH:mm:ss,或者具体的格式化类的全限定名
spring.jackson.deserialization:是否开启Jackson的反序列化
spring.jackson.generator:是否开启json的generators.
spring.jackson.joda-date-time-format:指定Joda date/time的格式,比如yyyy-MM-ddHH:mm:ss). 如果没有配置的话,dateformat会作为backup
spring.jackson.locale:指定json使用的Locale.
spring.jackson.mapper:是否开启Jackson通用的特性.
spring.jackson.parser:是否开启jackson的parser特性.
spring.jackson.property-naming-strategy:指定PropertyNamingStrategy(CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)或者指定PropertyNamingStrategy子类的全限定类名.
spring.jackson.serialization:是否开启jackson的序列化.
spring.jackson.serialization-inclusion:指定序列化时属性的inclusion方式,具体查看JsonInclude.Include枚举.
spring.jackson.time-zone:指定日期格式化时区,比如America/Los_Angeles或者GMT+10.
常用配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| spring: jackson: date-format: yyyy-MM-dd HH:mm:ss serialization: indent_output: true fail_on_empty_beans: false defaultPropertyInclusion: NON_EMPTY deserialization: fail_on_unknown_properties: false parser: allow_unquoted_control_chars: true allow_single_quotes: true
|
使用重新注入ObjectMapper
在配置bean中使用下面的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } }); return objectMapper; }
|