雪花Id发送给前端精度丢失

问题描述

后端 Id 使用雪花id, 发送给前端后精度丢失. 比如 后端id: 1336489934697050113, 发送到前端后, 变成: 1336489934697050000

问题分析

雪花 ID 是19 位, 而前端接收 Long 类型的是 Number, Number 的精度是16位, 这就导致了丢失数据

解决方案

后端把数据传给前端的时候, 把 Long 类型序列化成 String 类型, 这样前端就可以用 String 来接收数据了

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 全局配置序列化返回 JSON 处理
        SimpleModule simpleModule = new SimpleModule();
        // JSON Long ==> String
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐