springboot 針對(duì)jackson是自動(dòng)化配置的,如果需要修改,有兩種方式:
方式一:通過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會(huì)作為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指定序列化時(shí)屬性的inclusion方式,具體查看JsonInclude.Include枚舉.
spring.jackson.time-zone指定日期格式化時(shí)區(qū),比如America/Los_Angeles或者GMT+10.
常用配置:
spring: jackson: #日期格式化 date-format: yyyy-MM-dd HH:mm:ss serialization: #格式化輸出 indent_output: true #忽略無法轉(zhuǎn)換的對(duì)象 fail_on_empty_beans: false #設(shè)置空如何序列化 defaultPropertyInclusion: NON_EMPTY deserialization: #允許對(duì)象忽略json中不存在的屬性 fail_on_unknown_properties: false parser: #允許出現(xiàn)特殊字符和轉(zhuǎn)義符 allow_unquoted_control_chars: true #允許出現(xiàn)單引號(hào) allow_single_quotes: true
方式二:使用重新注入ObjectMapper
** 在配置bean中使用下面的配置 **
@Bean@Primary@ConditionalOnMissingBean(ObjectMapper.class)public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 通過該方法對(duì)mapper對(duì)象進(jìn)行設(shè)置,所有序列化的對(duì)象都將按改規(guī)則進(jìn)行系列化 // Include.Include.ALWAYS 默認(rèn) // Include.NON_DEFAULT 屬性為默認(rèn)值不序列化 // Include.NON_EMPTY 屬性為 空("") 或者為 NULL 都不序列化,則返回的json是沒有這個(gè)字段的。這樣對(duì)移動(dòng)端會(huì)更省流量 // Include.NON_NULL 屬性為NULL 不序列化 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 允許出現(xiàn)特殊字符和轉(zhuǎn)義符 objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // 允許出現(xiàn)單引號(hào) objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); // 字段保留,將null值轉(zhuǎn)為"" objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } }); return objectMapper; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選