修改Springboot默认序列化工具Jackson配置的实例代码

 更新时间:2024年02月22日 11:36:56   作者:wzytyt  
这篇文章主要介绍了如何修改Springboot默认序列化工具Jackson的配置,当Spring容器中存在多个同类型的Bean时,默认情况下最后一个创建的Bean将作为首选Bean,文中通过代码给大家介绍的非常详细,需要的朋友可以参考下

如果我们在Spring Boot应用中手动定义并注入了一个ObjectMapper Bean,那么这个自定义的ObjectMapper实例会替换掉Spring Boot默认配置的ObjectMapper。当Spring容器中存在多个同类型的Bean时,默认情况下最后一个创建的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转换等场景,都会使用到这个自定义配置的ObjectMapper,而非Spring Boot默认提供的那个。

因此,如果我们只想修改Spring Boot默认ObjectMapper的一些配置,而不是完全替换掉它,使用Jackson2ObjectMapperBuilderCustomizer接口是一个更好的选择。通过实现这个接口并注册一个定制器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自动配置创建的实例。这意味着在HTTP请求响应处理、消息转换等任何使用到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配置的实例代码的详细内容,更多关于修改Springboot Jackson配置的资料请关注脚本之家其它相关文章!

相关文章

  • SpringBoot整合Mail轻松实现邮件自动推送功能

    SpringBoot整合Mail轻松实现邮件自动推送功能

    在项目中经常会遇到SpringBoot推送消息的业务,除了站内推送通知,邮件推送也是一种常见的方式,本文小编就给大家介绍了SpringBoot整合Mail轻松实现邮件自动推送功能,需要的朋友可以参考下
    2024-12-12
  • springboot参数传中文乱码的解决方案

    springboot参数传中文乱码的解决方案

    这篇文章主要介绍了springboot参数传中文乱码的解决方案,帮助大家更好的理解和学习使用springboot,感兴趣的朋友可以了解下
    2021-03-03
  • SpringBoot日志信息以及Lombok的常用注解详析

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

    日志在我们的日常开发当中是必定会用到的,这篇文章主要给大家介绍了关于SpringBoot日志信息以及Lombok的常用注解的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-12-12
  • Java实现简易学生管理系统

    Java实现简易学生管理系统

    这篇文章主要为大家详细介绍了Java实现简易学生管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-07-07
  • Java中list.foreach不能使用字符串拼接的问题

    Java中list.foreach不能使用字符串拼接的问题

    这篇文章主要介绍了Java中list.foreach不能使用字符串拼接的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 详解Maven 搭建spring boot多模块项目(附源码)

    详解Maven 搭建spring boot多模块项目(附源码)

    这篇文章主要介绍了详解Maven 搭建spring boot多模块项目(附源码),具有一定的参考价值,有兴趣的可以了解一下
    2017-09-09
  • SpringBoot 读取yml文件的多种方式汇总

    SpringBoot 读取yml文件的多种方式汇总

    这篇文章主要介绍了SpringBoot读取yml文件的几种方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • PowerJob的UserService工作流程源码解读

    PowerJob的UserService工作流程源码解读

    这篇文章主要介绍了PowerJob的UserService工作流程源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • maven profile动态选择配置文件详解

    maven profile动态选择配置文件详解

    这篇文章主要介绍了maven profile动态选择配置文件详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • idea自动加载html、js而无需重启进程的操作

    idea自动加载html、js而无需重启进程的操作

    这篇文章主要介绍了idea自动加载html、js而无需重启进程的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08

最新评论