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