SpringBoot Long型数据丢失精度问题

原创
2021/01/14 16:09
阅读数 2K

方案一,在application.yml添加以下配置

spring:
  jackson: 
    generator:
     ## 将数值类型转换为字符串,解决long型精度丢失
      write_numbers_as_strings: true

返回结果是可以的,不过这个针对全局的number类型的数据全部转化为string,慎用!!!

方案二,这个比上面那个方案更细致一点,可以针对全局的只有Long类型的做处理即可


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

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

@Configuration
public class JsonMessageConverter{
 
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化。
        //JsonInclude.Include.NON_NULL 属性为NULL 不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //jackson中自定义处理序列化和反序列化
        SimpleModule module = new SimpleModule();
        //Method for adding serializer to handle values of specific type.
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        //register the module with the object-mapper
        objectMapper.registerModule(module);
        return objectMapper;
    }
}

亲测有效,推荐此方案。

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部