提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.jackson.config;
H 2
3 import cn.hutool.core.collection.CollUtil;
4 import com.iailab.framework.common.util.json.JsonUtils;
5 import com.fasterxml.jackson.databind.ObjectMapper;
6 import com.fasterxml.jackson.databind.module.SimpleModule;
7 import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
8 import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
9 import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
10 import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
325d2f 11 import com.iailab.framework.common.util.json.databind.NumberSerializer;
H 12 import com.iailab.framework.common.util.json.databind.TimestampLocalDateTimeDeserializer;
13 import com.iailab.framework.common.util.json.databind.TimestampLocalDateTimeSerializer;
e7c126 14 import lombok.extern.slf4j.Slf4j;
H 15 import org.springframework.boot.autoconfigure.AutoConfiguration;
16 import org.springframework.context.annotation.Bean;
17
18 import java.time.LocalDate;
19 import java.time.LocalDateTime;
20 import java.time.LocalTime;
21 import java.util.List;
22
23 @AutoConfiguration
24 @Slf4j
25 public class IailabJacksonAutoConfiguration {
26
27     @Bean
28     @SuppressWarnings("InstantiationOfUtilityClass")
29     public JsonUtils jsonUtils(List<ObjectMapper> objectMappers) {
30         // 1.1 创建 SimpleModule 对象
31         SimpleModule simpleModule = new SimpleModule();
32         simpleModule
33                 // 新增 Long 类型序列化规则,数值超过 2^53-1,在 JS 会出现精度丢失问题,因此 Long 自动序列化为字符串类型
34                 .addSerializer(Long.class, NumberSerializer.INSTANCE)
35                 .addSerializer(Long.TYPE, NumberSerializer.INSTANCE)
36                 .addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE)
37                 .addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE)
38                 .addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE)
39                 .addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE)
40                 // 新增 LocalDateTime 序列化、反序列化规则,使用 Long 时间戳
41                 .addSerializer(LocalDateTime.class, TimestampLocalDateTimeSerializer.INSTANCE)
42                 .addDeserializer(LocalDateTime.class, TimestampLocalDateTimeDeserializer.INSTANCE);
43         // 1.2 注册到 objectMapper
44         objectMappers.forEach(objectMapper -> objectMapper.registerModule(simpleModule));
45
46         // 2. 设置 objectMapper 到 JsonUtils
47         JsonUtils.init(CollUtil.getFirst(objectMappers));
48         log.info("[init][初始化 JsonUtils 成功]");
49         return new JsonUtils();
50     }
51
52 }