修改Springboot默認(rèn)序列化工具Jackson配置的實(shí)例代碼
如果我們?cè)赟pring Boot應(yīng)用中手動(dòng)定義并注入了一個(gè)ObjectMapper Bean,那么這個(gè)自定義的ObjectMapper實(shí)例會(huì)替換掉Spring Boot默認(rèn)配置的ObjectMapper。當(dāng)Spring容器中存在多個(gè)同類(lèi)型的Bean時(shí),默認(rèn)情況下最后一個(gè)創(chuàng)建的Bean將作為首選Bean(如果未明確指定@Primary注解),因此我們的自定義ObjectMapper將會(huì)被所有依賴(lài)于ObjectMapper的地方使用。
例如:
@Configuration
public class ObjectMapperConfig {
@Bean
public ObjectMapper customObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 添加自定義配置...
return objectMapper;
}
}
上述代碼定義了一個(gè)自定義的ObjectMapper Bean,并將其注冊(cè)到了Spring容器中。這樣一來(lái),在整個(gè)應(yīng)用中需要ObjectMapper的地方,包括HTTP請(qǐng)求和響應(yīng)的JSON轉(zhuǎn)換等場(chǎng)景,都會(huì)使用到這個(gè)自定義配置的ObjectMapper,而非Spring Boot默認(rèn)提供的那個(gè)。
因此,如果我們只想修改Spring Boot默認(rèn)ObjectMapper的一些配置,而不是完全替換掉它,使用Jackson2ObjectMapperBuilderCustomizer接口是一個(gè)更好的選擇。通過(guò)實(shí)現(xiàn)這個(gè)接口并注冊(cè)一個(gè)定制器Bean,我們可以對(duì)默認(rèn)的ObjectMapper進(jìn)行擴(kuò)展和修改,而不會(huì)覆蓋其他默認(rèn)配置。
下面是一個(gè)例子:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return builder -> {
// 修改日期格式化
builder.dateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// 關(guān)閉未知屬性導(dǎo)致反序列化失敗
builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 其他自定義配置...
};
}
}
這樣,我們的配置將應(yīng)用于所有的ObjectMapper實(shí)例,包括那些由Spring Boot自動(dòng)配置創(chuàng)建的實(shí)例。這意味著在HTTP請(qǐng)求響應(yīng)處理、消息轉(zhuǎn)換等任何使用到ObjectMapper的地方,都會(huì)采用我們自定義的配置。
另外,Jackson2ObjectMapperBuilderCustomizer接口并不能配置空值序列化操作,因此我們可以這樣:
// 該方式不會(huì)完全替換Springboot默認(rèn)的ObjectMapper,并且可以設(shè)置空值序列化器
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
builder.modules(getJavaLongSimpleModule(), getJavaTimeSimpleModule());
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
return objectMapper;
}
該方式不會(huì)完全替換Springboot默認(rèn)的ObjectMapper,并且可以設(shè)置空值序列化器。
注:JsonSerializer無(wú)法在序列化時(shí)對(duì)空值操作,因?yàn)槠?code>serialize方法接收到的被序列化對(duì)象永遠(yuǎn)不為null
/**
* Abstract class that defines API used by {@link ObjectMapper} (and
* other chained {@link JsonSerializer}s too) to serialize Objects of
* arbitrary types into JSON, using provided {@link JsonGenerator}.
* {@link com.fasterxml.jackson.databind.ser.std.StdSerializer} instead
* of this class, since it will implement many of optional
* methods of this class.
*<p>
* NOTE: various <code>serialize</code> methods are never (to be) called
* with null values -- caller <b>must</b> handle null values, usually
* by calling {@link SerializerProvider#findNullValueSerializer} to obtain
* serializer to use.
* This also means that custom serializers cannot be directly used to change
* the output to produce when serializing null values.
*<p>
* If serializer is an aggregate one -- meaning it delegates handling of some
* of its contents by using other serializer(s) -- it typically also needs
* to implement {@link com.fasterxml.jackson.databind.ser.ResolvableSerializer},
* which can locate secondary serializers needed. This is important to allow dynamic
* overrides of serializers; separate call interface is needed to separate
* resolution of secondary serializers (which may have cyclic link back
* to serializer itself, directly or indirectly).
*<p>
* In addition, to support per-property annotations (to configure aspects
* of serialization on per-property basis), serializers may want
* to implement
* {@link com.fasterxml.jackson.databind.ser.ContextualSerializer},
* which allows specialization of serializers: call to
* {@link com.fasterxml.jackson.databind.ser.ContextualSerializer#createContextual}
* is passed information on property, and can create a newly configured
* serializer for handling that particular property.
*<p>
* If both
* {@link com.fasterxml.jackson.databind.ser.ResolvableSerializer} and
* {@link com.fasterxml.jackson.databind.ser.ContextualSerializer}
* are implemented, resolution of serializers occurs before
* contextualization.
*/
public abstract class JsonSerializer<T> implements JsonFormatVisitable // since 2.1
{
/**
* Method that can be called to ask implementation to serialize
* values of type this serializer handles.
*
* @param value Value to serialize; can <b>not</b> be null.
* @param gen Generator used to output resulting Json content
* @param serializers Provider that can be used to get serializers for
* serializing Objects value contains, if any.
*/
public abstract void serialize(T value, JsonGenerator gen, SerializerProvider serializers)
throws IOException;
}
以上就是修改Springboot默認(rèn)序列化工具Jackson配置的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于修改Springboot Jackson配置的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一篇文章帶你理解Java Spring三級(jí)緩存和循環(huán)依賴(lài)
這篇文章主要介紹了淺談Spring 解決循環(huán)依賴(lài)必須要三級(jí)緩存嗎,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-09-09
dubbo環(huán)境搭建ZooKeeper注冊(cè)中心全過(guò)程
文章介紹Dubbo環(huán)境搭建,包含ZooKeeper注冊(cè)中心的安裝配置(修改數(shù)據(jù)存儲(chǔ)路徑、啟動(dòng)服務(wù)并驗(yàn)證節(jié)點(diǎn))和dubbo-admin監(jiān)控中心的部署流程(解壓、打包、運(yùn)行jar包,需注意Maven版本及zkServer狀態(tài))2025-07-07
IDEA中的Run/Debug Configurations各項(xiàng)解讀
這篇文章主要介紹了IDEA中的Run/Debug Configurations各項(xiàng)解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
詳解SpringBoot 添加對(duì)JSP的支持(附常見(jiàn)坑點(diǎn))
這篇文章主要介紹了詳解SpringBoot 添加對(duì)JSP的支持(附常見(jiàn)坑點(diǎn)),非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-10-10
idea中使用SonarLint進(jìn)行代碼規(guī)范檢測(cè)及使用方法
這篇文章主要介紹了idea中使用SonarLint進(jìn)行代碼規(guī)范檢測(cè),本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
解決idea使用過(guò)程中讓你覺(jué)得不爽的一些問(wèn)題(小結(jié))
這篇文章主要介紹了解決idea使用過(guò)程中讓你覺(jué)得不爽的一些問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

