修改Springboot默認序列化工具Jackson配置的實例代碼
如果我們在Spring Boot應用中手動定義并注入了一個ObjectMapper Bean,那么這個自定義的ObjectMapper實例會替換掉Spring Boot默認配置的ObjectMapper。當Spring容器中存在多個同類型的Bean時,默認情況下最后一個創(chuàng)建的Bean將作為首選Bean(如果未明確指定@Primary注解),因此我們的自定義ObjectMapper將會被所有依賴于ObjectMapper的地方使用。
例如:
@Configuration
public class ObjectMapperConfig {
@Bean
public ObjectMapper customObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 添加自定義配置...
return objectMapper;
}
}
上述代碼定義了一個自定義的ObjectMapper Bean,并將其注冊到了Spring容器中。這樣一來,在整個應用中需要ObjectMapper的地方,包括HTTP請求和響應的JSON轉(zhuǎn)換等場景,都會使用到這個自定義配置的ObjectMapper,而非Spring Boot默認提供的那個。
因此,如果我們只想修改Spring Boot默認ObjectMapper的一些配置,而不是完全替換掉它,使用Jackson2ObjectMapperBuilderCustomizer接口是一個更好的選擇。通過實現(xiàn)這個接口并注冊一個定制器Bean,我們可以對默認的ObjectMapper進行擴展和修改,而不會覆蓋其他默認配置。
下面是一個例子:
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");
// 關閉未知屬性導致反序列化失敗
builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 其他自定義配置...
};
}
}
這樣,我們的配置將應用于所有的ObjectMapper實例,包括那些由Spring Boot自動配置創(chuàng)建的實例。這意味著在HTTP請求響應處理、消息轉(zhuǎn)換等任何使用到ObjectMapper的地方,都會采用我們自定義的配置。
另外,Jackson2ObjectMapperBuilderCustomizer接口并不能配置空值序列化操作,因此我們可以這樣:
// 該方式不會完全替換Springboot默認的ObjectMapper,并且可以設置空值序列化器
@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默認的ObjectMapper,并且可以設置空值序列化器。
注:JsonSerializer無法在序列化時對空值操作,因為其serialize方法接收到的被序列化對象永遠不為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默認序列化工具Jackson配置的實例代碼的詳細內(nèi)容,更多關于修改Springboot Jackson配置的資料請關注腳本之家其它相關文章!
相關文章
SpringBoot整合Mail輕松實現(xiàn)郵件自動推送功能
在項目中經(jīng)常會遇到SpringBoot推送消息的業(yè)務,除了站內(nèi)推送通知,郵件推送也是一種常見的方式,本文小編就給大家介紹了SpringBoot整合Mail輕松實現(xiàn)郵件自動推送功能,需要的朋友可以參考下2024-12-12
Java中l(wèi)ist.foreach不能使用字符串拼接的問題
這篇文章主要介紹了Java中l(wèi)ist.foreach不能使用字符串拼接的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
詳解Maven 搭建spring boot多模塊項目(附源碼)
這篇文章主要介紹了詳解Maven 搭建spring boot多模塊項目(附源碼),具有一定的參考價值,有興趣的可以了解一下2017-09-09

