修改Springboot默認(rèn)序列化工具Jackson配置的實例代碼
如果我們在Spring Boot應(yīng)用中手動定義并注入了一個ObjectMapper Bean,那么這個自定義的ObjectMapper實例會替換掉Spring Boot默認(rèn)配置的ObjectMapper。當(dāng)Spring容器中存在多個同類型的Bean時,默認(rèn)情況下最后一個創(chuàng)建的Bean將作為首選Bean(如果未明確指定@Primary注解),因此我們的自定義ObjectMapper將會被所有依賴于ObjectMapper的地方使用。
例如:
@Configuration
public class ObjectMapperConfig {
@Bean
public ObjectMapper customObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 添加自定義配置...
return objectMapper;
}
}
上述代碼定義了一個自定義的ObjectMapper Bean,并將其注冊到了Spring容器中。這樣一來,在整個應(yīng)用中需要ObjectMapper的地方,包括HTTP請求和響應(yīng)的JSON轉(zhuǎn)換等場景,都會使用到這個自定義配置的ObjectMapper,而非Spring Boot默認(rèn)提供的那個。
因此,如果我們只想修改Spring Boot默認(rèn)ObjectMapper的一些配置,而不是完全替換掉它,使用Jackson2ObjectMapperBuilderCustomizer接口是一個更好的選擇。通過實現(xiàn)這個接口并注冊一個定制器Bean,我們可以對默認(rèn)的ObjectMapper進(jìn)行擴(kuò)展和修改,而不會覆蓋其他默認(rèn)配置。
下面是一個例子:
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實例,包括那些由Spring Boot自動配置創(chuàng)建的實例。這意味著在HTTP請求響應(yīng)處理、消息轉(zhuǎn)換等任何使用到ObjectMapper的地方,都會采用我們自定義的配置。
另外,Jackson2ObjectMapperBuilderCustomizer接口并不能配置空值序列化操作,因此我們可以這樣:
// 該方式不會完全替換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;
}
該方式不會完全替換Springboot默認(rèn)的ObjectMapper,并且可以設(shè)置空值序列化器。
注:JsonSerializer無法在序列化時對空值操作,因為其serialize方法接收到的被序列化對象永遠(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配置的實例代碼的詳細(xì)內(nèi)容,更多關(guān)于修改Springboot Jackson配置的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一篇文章帶你理解Java Spring三級緩存和循環(huán)依賴
這篇文章主要介紹了淺談Spring 解決循環(huán)依賴必須要三級緩存嗎,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-09-09
dubbo環(huán)境搭建ZooKeeper注冊中心全過程
文章介紹Dubbo環(huán)境搭建,包含ZooKeeper注冊中心的安裝配置(修改數(shù)據(jù)存儲路徑、啟動服務(wù)并驗證節(jié)點)和dubbo-admin監(jiān)控中心的部署流程(解壓、打包、運(yùn)行jar包,需注意Maven版本及zkServer狀態(tài))2025-07-07
IDEA中的Run/Debug Configurations各項解讀
這篇文章主要介紹了IDEA中的Run/Debug Configurations各項解讀,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
idea中使用SonarLint進(jìn)行代碼規(guī)范檢測及使用方法
這篇文章主要介紹了idea中使用SonarLint進(jìn)行代碼規(guī)范檢測,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08
解決idea使用過程中讓你覺得不爽的一些問題(小結(jié))
這篇文章主要介紹了解決idea使用過程中讓你覺得不爽的一些問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

