Skip to content

后端处理精度丢失问题

约 176 字小于 1 分钟

SpringBoot

2025-03-04

本文作者:程序员飞云

本站地址:https://www.flycode.icu

精度丢失问题

在前端接受Long类型的数据时,发现精度丢失了,但是实际上数据是没问题的,这个可以在前端处理也可以在后端处理。

后端处理

主要就是使用jackson将Long类型转换为String给前端

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * Spring MVC Json 配置
 */
@JsonComponent
public class JsonConfig {

    /**
     * 添加 Long  json 精度丢失的配置
     */
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        return objectMapper;
    }
}

贡献者

  • flycodeuflycodeu

公告板

2025-03-04正式迁移知识库到此项目