成都哪里有做网站的,wordpress本地登录密码,百度小程序开发平台,wordpress 置顶文章文章目录 精度丢失的具体原因解决方法1. 使用 JsonSerialize 和 ToStringSerializer2. 使用 JsonFormat 注解3. 全局配置解决方案 结论 开发商城管理系统的品牌管理界面时#xff0c;发现一个问题#xff0c;接口返回品牌Id和页面展示的品牌Id不一致#xff0c;如接口返回的… 文章目录 精度丢失的具体原因解决方法1. 使用 JsonSerialize 和 ToStringSerializer2. 使用 JsonFormat 注解3. 全局配置解决方案 结论 开发商城管理系统的品牌管理界面时发现一个问题接口返回品牌Id和页面展示的品牌Id不一致如接口返回的是1816714744603811841前端战胜的是1816714744603811800。
这是因为在前端出现了数据精度丢失。
精度丢失的具体原因
JavaScript的Number类型用于表示浮点数它遵循IEEE 754标准中的64位浮点数格式。这意味着它能够准确表示从(-2{53})到(2{53}-1)之间的所有整数。超出这个范围的整数值在转换为Number类型时可能会发生精度丢失即原本不同的长整数会被转换成相同的浮点数值从而导致数据失真。
解决方法
为了解决品牌ID在前后端传输过程中精度丢失的问题可以采用以下几种解决方法
1. 使用 JsonSerialize 和 ToStringSerializer
在Java后端中可以通过使用Jackson库的注解功能将Long类型的字段在序列化为JSON时转换为String类型。这样前端接收到的数据是字符串形式避免了精度丢失的问题。
示例代码:
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;Data
public class BrandVo {// 使用ToStringSerializer将Long类型的id字段转换为String类型JsonSerialize(using ToStringSerializer.class)private Long id;// 其他字段...
}通过这种方式我们可以确保后端返回的JSON中Long类型的字段都以字符串的形式存在前端可以直接将其作为字符串处理无需担心精度问题。
2. 使用 JsonFormat 注解
除了使用 ToStringSerializerJackson还提供了 JsonFormat 注解它允许指定字段的序列化格式。当将 shape 属性设置为 JsonFormat.Shape.STRING 时Long类型的字段会被格式化为字符串。
示例代码:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;Data
public class BrandVo {// 使用JsonFormat注解将Long类型的id字段格式化为StringJsonFormat(shape JsonFormat.Shape.STRING)private Long id;// 其他字段...
}这种方法同样可以确保Long类型的字段在序列化为JSON时以字符串形式出现避免前端精度丢失的问题。
3. 全局配置解决方案
虽然使用注解可以在一定程度上解决问题但对于大型项目逐个字段添加注解不仅繁琐还可能导致代码冗余和难以维护。因此可以考虑使用全局配置的方式一次性解决所有Long类型字段的序列化问题。
示例代码:
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.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;Configuration
public class JacksonConfig {BeanPrimaryConditionalOnMissingBean(ObjectMapper.class)public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {ObjectMapper objectMapper builder.createXmlMapper(false).build();SimpleModule simpleModule new SimpleModule();// 将Long类型序列化为String类型simpleModule.addSerializer(Long.class, ToStringSerializer.instance);objectMapper.registerModule(simpleModule);return objectMapper;}
}在这个配置中我们创建了一个自定义的ObjectMapper Bean并注册了一个SimpleModule该模块使用ToStringSerializer将Long类型序列化为String类型。这样整个应用中所有Long类型的字段在序列化时都会自动转换为String类型。
结论
前端精度丢失问题是一个常见的挑战但通过上述三种方法我们可以有效地解决这个问题。在实际开发中我们可以根据项目的具体情况和需求选择合适的方法。对于需要精确表示大数字的场景将Long类型转换为String类型是一个简单而有效的解决方案。