骑士の物语
>
SpringBoot 中的 Json 格式化配置
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-dd HH: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。
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中使用下面的配置
@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; }
|