jackson解决Long类型丢失精度问题

1.问题出现原因

问题出现的原因是JavaScript只能对16位以内长度字符可以保证精度如果超过则无法保持精度,例如后端返回给前端ID超过16位则会丢失精度

2.解决方案

后端在给前端返回数据ID时将Long类型转换为String字符串,如果前端拿到的是字符串则不会丢失精度,然后用户在根据此ID进行查询时,向后端发送的是字符串,那么后端对字符串进行解析转换成Long或者Integer就好了

3.具体实现

方案一

在具体ID上添加注解标记此ID使用JsonFormat序列化

public class user implements Serializable {
    //方式一
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private Long id;
    private String username;
    private String password;

方案二

在具体ID上添加注解标记此ID使用JsonFormat序列化

public class user implements Serializable {
    //方式二
    @JsonSerialize(using = ToStringSerializer.class)
    private String userId;

综上两种解决方案都需要初始化到IOC容器中(在SpringBoot启动类加上)

 @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
        ObjectMapper build = mapperBuilder.createXmlMapper(false).build();
        build.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule module = new SimpleModule();	
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        build.registerModule(module);
        return build;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值