java jackson2.6_Jackson序列化(2)— [SpringBoot2.x]-Spring容器中ObjectMapper

本文介绍了SpringBoot2.x如何自动装载并配置Jackson的ObjectMapper,强调了不应将自定义的ObjectMapper放入Spring容器以免覆盖默认配置。SpringBoot2.x通过Jackson2ObjectMapperBuilder在容器中创建ObjectMapper,可以通过yml配置文件或实现Jackson2ObjectMapperBuilderCustomizer接口来修改其配置。文章详细展示了配置和修改ObjectMapper的方法,包括配置文件修改和Java代码配置。
摘要由CSDN通过智能技术生成

上文说到,SpringBoot2.x会自动装载MappingJackson2HttpMessageConverter进行消息转换。而MappingJackson2HttpMessageConverter会获取Spring容器中的ObjectMapper配置,来进行Jackson的序列化和反序列化。

注意:在SpringBoot2.x环境下,不要将自定义的ObjectMapper对象放入Spring容器!这样会将原有的ObjectMapper配置覆盖。

ObjectMapper是JSON操作的核心,Jackson的JSON操作都是在ObjectMapper中实现的。

1. SpringBoot2.x中的ObjectMapper

SpringBoot2.x默认装载了ObjectMapper到Spring容器,在yml配置文件中使用spring.jackson为前缀的配置可以修改,也可以在代码中实现Jackson2ObjectMapperBuilderCustomizer接口去修改ObjectMapper配置。

@Configuration

//注解通俗的说就是Spring工程中引用了Jackson的包 才会构建这个bean

@ConditionalOnClass(ObjectMapper.class)

public class JacksonAutoConfiguration {

//默认的feature配置

private static final Map, Boolean> FEATURE_DEFAULTS;

//SpringBoot2.x配置WRITE_DATES_AS_TIMESTAMPS=false,即Date日期不会转换为时间戳类型

static {

Map featureDefaults = new HashMap<>();

featureDefaults.put(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

FEATURE_DEFAULTS = Collections.unmodifiableMap(featureDefaults);

}

@Bean

public JsonComponentModule jsonComponentModule() {

return new JsonComponentModule();

}

@Configuration

@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)

static class JacksonObjectMapperConfiguration {

@Bean

@Primary

//若自定义ObjectMapper放入Spring容器中,该配置不会生效!

@ConditionalOnMissingBean

//获取Spring容器中的Jackson2ObjectMapperBuilder 。

public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {

return builder.createXmlMapper(false).build();

}

}

@Configuration

@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)

static class JacksonObjectMapperBuilderConfiguration {

private final ApplicationContext applicationContext;

JacksonObjectMapperBuilderConfiguration(ApplicationContext applicationContext) {

this.applicationCon

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值