欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

修改Springboot默認序列化工具Jackson配置的實例代碼

 更新時間:2024年02月22日 11:36:56   作者:wzytyt  
這篇文章主要介紹了如何修改Springboot默認序列化工具Jackson的配置,當Spring容器中存在多個同類型的Bean時,默認情況下最后一個創(chuàng)建的Bean將作為首選Bean,文中通過代碼給大家介紹的非常詳細,需要的朋友可以參考下

如果我們在Spring Boot應(yīng)用中手動定義并注入了一個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容器中。這樣一來,在整個應(yīng)用中需要ObjectMapper的地方,包括HTTP請求和響應(yīng)的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");
            
            // 關(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默認的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默認的ObjectMapper,并且可以設(shè)置空值序列化器。

注: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)容,更多關(guān)于修改Springboot Jackson配置的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • SpringBoot整合Mail輕松實現(xiàn)郵件自動推送功能

    SpringBoot整合Mail輕松實現(xiàn)郵件自動推送功能

    在項目中經(jīng)常會遇到SpringBoot推送消息的業(yè)務(wù),除了站內(nèi)推送通知,郵件推送也是一種常見的方式,本文小編就給大家介紹了SpringBoot整合Mail輕松實現(xiàn)郵件自動推送功能,需要的朋友可以參考下
    2024-12-12
  • springboot參數(shù)傳中文亂碼的解決方案

    springboot參數(shù)傳中文亂碼的解決方案

    這篇文章主要介紹了springboot參數(shù)傳中文亂碼的解決方案,幫助大家更好的理解和學(xué)習(xí)使用springboot,感興趣的朋友可以了解下
    2021-03-03
  • SpringBoot日志信息以及Lombok的常用注解詳析

    SpringBoot日志信息以及Lombok的常用注解詳析

    日志在我們的日常開發(fā)當中是必定會用到的,這篇文章主要給大家介紹了關(guān)于SpringBoot日志信息以及Lombok的常用注解的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-12-12
  • Java實現(xiàn)簡易學(xué)生管理系統(tǒng)

    Java實現(xiàn)簡易學(xué)生管理系統(tǒng)

    這篇文章主要為大家詳細介紹了Java實現(xiàn)簡易學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-07-07
  • Java中l(wèi)ist.foreach不能使用字符串拼接的問題

    Java中l(wèi)ist.foreach不能使用字符串拼接的問題

    這篇文章主要介紹了Java中l(wèi)ist.foreach不能使用字符串拼接的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 詳解Maven 搭建spring boot多模塊項目(附源碼)

    詳解Maven 搭建spring boot多模塊項目(附源碼)

    這篇文章主要介紹了詳解Maven 搭建spring boot多模塊項目(附源碼),具有一定的參考價值,有興趣的可以了解一下
    2017-09-09
  • SpringBoot?讀取yml文件的多種方式匯總

    SpringBoot?讀取yml文件的多種方式匯總

    這篇文章主要介紹了SpringBoot讀取yml文件的幾種方式,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-05-05
  • PowerJob的UserService工作流程源碼解讀

    PowerJob的UserService工作流程源碼解讀

    這篇文章主要介紹了PowerJob的UserService工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • maven profile動態(tài)選擇配置文件詳解

    maven profile動態(tài)選擇配置文件詳解

    這篇文章主要介紹了maven profile動態(tài)選擇配置文件詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • idea自動加載html、js而無需重啟進程的操作

    idea自動加載html、js而無需重啟進程的操作

    這篇文章主要介紹了idea自動加載html、js而無需重啟進程的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08

最新評論