背景

  1. 问题1:项目中使用默认自带的jackson进行前后端交互,实现数据对象的序列化和反序列化,默认的ObjectMapper采用小驼峰的格式,但是调用其他业务的http接口时,ObjectMapper需要使用蛇形的格式,因此就需要自定义ObjectMapper,然后封装RestTemplate。
  2. 问题2:前后端交互时,JSR310日期序列化时,格式错误;使用springboot自带的jackson,是不支持JSR310的日期,需要全局配置

注意点

  1. 自定义的ObjectMapper不能被IOC管理,因为Springboot默认的ObjectMapper生成条件是:只有当该实例不存在的时候才会创建!
  2. 自定义时,需要支持JSR310的日期,否则序列化LocalDateTime、LocalDate、LocalTime时,就会返回错误的格式。

自定义ObjectMapper

@Slf4j
public class JsonFormatUtils {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
public static final ObjectMapper objectMapper = new ObjectMapper(); static {
//取消时间的转化格式,默认是时间戳,同时需要设置要表现的时间格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
JavaTimeModule javaTimeModule = new JavaTimeModule(); // 默认序列化没有实现,反序列化有实现
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DATE_FORMATTER));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(TIME_FORMATTER));
objectMapper.registerModule(javaTimeModule);
// 设置时区
objectMapper.setTimeZone(TimeZone.getDefault());
// 设置格式化输出
// objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// 设置蛇形格式
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
} public static String writeValueAsString(Object obj) {
String result = null;
try {
result = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("objectMapper writeValueAsString exception, e:", e);
}
return result;
} public static <T> T readValue(String str, Class<T> tClass) {
T t = null;
try {
t = objectMapper.readValue(str, tClass);
} catch (JsonProcessingException e) {
log.error("objectMapper readValue exception, e:", e);
}
return t;
}
}

封装RestTemplate

@Configuration
public class RestTemplateConfig {
@Bean("otherRestTemplate")
public RestTemplate algoRestTemplate() {
// 使用apache的httpComponents,封装restTemplate
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
RestTemplate restTemplate = new RestTemplate(factory);
// 使用自定义的ObjectMapper
ObjectMapper objectMapper = JsonFormatUtils.objectMapper;
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(false);
messageConverter.setObjectMapper(objectMapper); List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
messageConverters.removeIf(item -> item.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
messageConverters.add(messageConverter);
return restTemplate;
} private HttpClient httpClient() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(50);
connectionManager.setDefaultMaxPerRoute(10);
connectionManager.setValidateAfterInactivity(2000);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.build();
return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
}
}

全局配置

底层默认是通过Jackson2ObjectMapperBuilderCustomizer创建的ObjectMapper

@Configuration
public class LocalDateTimeSerializerConfig { private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss"); @Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Map<Class<?>, JsonSerializer<?>> serializers = new HashMap<>();
serializers.put(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER));
serializers.put(LocalDate.class, new LocalDateSerializer(DATE_FORMATTER));
serializers.put(LocalTime.class, new LocalTimeSerializer(TIME_FORMATTER)); Map<Class<?>, JsonDeserializer<?>> deserializers = new HashMap<>();
deserializers.put(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER));
deserializers.put(LocalDate.class, new LocalDateDeserializer(DATE_FORMATTER));
deserializers.put(LocalTime.class, new LocalTimeDeserializer(TIME_FORMATTER));
return builder -> builder.serializersByType(serializers).deserializersByType(deserializers);
}
}

springboot自定义ObjectMapper序列化、配置序列化对LocalDateTime的支持的更多相关文章

  1. SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

    场景及需求: 项目接入了SpringBoot开发,现在需求是服务端接口返回的字段如果为空,那么自动转为空字符串. 例如: [     {         "id": 1,      ...

  2. 【转】SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

    场景及需求: 项目接入了SpringBoot开发,现在需求是服务端接口返回的字段如果为空,那么自动转为空字符串. 例如:[     {         "id": 1,       ...

  3. Spring Boot 结合 Redis 序列化配置的一些问题

    前言 最近在学习Spring Boot结合Redis时看了一些网上的教程,发现这些教程要么比较老,要么不知道从哪抄得,运行起来有问题.这里分享一下我最新学到的写法 默认情况下,Spring 为我们提供 ...

  4. 【SpringBoot】 中时间类型 序列化、反序列化、格式处理

    [SpringBoot] 中时间类型 序列化.反序列化.格式处理 Date yml全局配置 spring: jackson: time-zone: GMT+8 date-format: yyyy-MM ...

  5. 如何使用Externalizable接口自定义Java中的序列化

    Java序列化过程的缺点 我们都知道如何使用Serializable接口序列化/反序列化一个对象,并且如何使用writeObject 和readObject方法自定义序列化过程. 但是这些自定义还不够 ...

  6. Springboot中以配置类方式自定义Mybatis的配置规则(如开启驼峰映射等)

    什么是自定义Mybatis的配置规则? 答:即原来在mybatis配置文件中中我们配置到<settings>标签中的内容,如下第6-10行内容: 1 <?xml version=&q ...

  7. Java之SpringBoot自定义配置与整合Druid

    Java之SpringBoot自定义配置与整合Druid SpringBoot配置文件 优先级 前面SpringBoot基础有提到,关于SpringBoot配置文件可以是properties或者是ya ...

  8. SpringBoot扩展SpringMVC自动配置

    SpringBoot中自动配置了 ViewResolver(视图解析器) ContentNegotiatingViewResolver(组合所有的视图解析器) 自动配置了静态资源文件夹.静态首页.fa ...

  9. SpringBoot + Redis:基本配置及使用

    注:本篇博客SpringBoot版本为2.1.5.RELEASE,SpringBoot1.0版本有些配置不适用 一.SpringBoot 配置Redis 1.1 pom 引入spring-boot-s ...

随机推荐

  1. js更改HTML样式

    <!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content=&q ...

  2. Linux中mail的用法

    简介:mail命令是命令行的电子邮件发送和接收工具.操作的界面不像elm或pine那么容易使用,但功能非常完整Red Hat上sendmail服务一般是自动启动的.可以通过下面的命令查看sendmai ...

  3. 3、dns服务搭建

    3.1.dns服务简介: 1.DNS(Domain Name System)域名系统. 目前提供网络服务的应用使用唯一的32位的IP地址来标识,但是由于数字比较复杂.难以记忆,因此产生了域名系统(DN ...

  4. sys用户权限不足,本地登录失败 |ORA-01031 insufficient privileges|

    机器总喜欢挑放假的时候出问题,"双节"(中秋.国庆)快到了,对于搞系统运维的工程师来说其实并不轻松,于是今天赶紧装起一台数据库备用服务器以备半夜"机"叫. 安装 ...

  5. hdu 6030 矩阵快速幂

    大致题意: 一条长度为n的项链,由红色珠子和蓝色珠子(分别用1和0表示)组成,在连续的素数子段中,红色珠子的个数不能少于蓝色珠子.问组成这个项链有多少种方案,求方案数模1000000007 分析: 首 ...

  6. AcWing 1128. 信使

    战争时期,前线有 n个哨所,每个哨所可能会与其他若干个哨所之间有通信联系. 信使负责在哨所之间传递信息,当然,这是要花费一定时间的(以天为单位). 指挥部设在第一个哨所.当指挥部下达一个命令后,指挥部 ...

  7. AcWing 220. 最大公约数

    给定整数N,求1<=x,y<=N且GCD(x,y)为素数的数对(x,y)有多少对. GCD(x,y)即求x,y的最大公约数. #include<bits/stdc++.h> u ...

  8. linux修改 ls 命令的时间显示格式

    一直不习惯 ll 命令将时间日期格式显示为 周名和月名,想要纯粹的 数字格式,找了好久,终于想到一个办法--alias. [root@localhost ~]# alias #显示当前已存在的alia ...

  9. java.lang.Excetion,java.lang.RuntimeException,java.lang.Error有什么区别?

    Error类对象由Java虚拟机生成并抛出,Exception类对象由应用程序处理或抛出 Error表示恢复不是不可能但很困难的情况下的一种严重问题.比如说内存溢出.不可能指望程序能处理这样的情况. ...

  10. Linux文件目录结构详解 (转)

      整理自<鸟哥的私房菜> 对于每一个Linux学习者来说,了解Linux文件系统的目录结构,是学好Linux的至关重要的一步.,深入了解linux文件目录结构的标准和每个目录的详细功能, ...