1. 程式人生 > 其它 >解決前後端互動Long型別精度丟失的問題

解決前後端互動Long型別精度丟失的問題

一、現象與分析
1.1. 現象
雪花演算法得到的ID較長,傳到前端後,精度丟失,導致更新、刪除功能不可用
1.2. 分析
庫中存的值:23754851322302474
後端取的值:23754851322302474
前端得到值:23754851322302470,資料被四捨五入了

二、解決方案

    將Long型別轉成String,再傳給前端

2.1. 方法一單個註解
@JsonSerialize(using= ToStringSerializer.class)
private Long id;

2.2. 方法二統一配置
package com.jiawa.wiki.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/** * 統一註解,解決前後端互動Long型別精度丟失的問題 */ @Configuration public class JacksonConfig { @Bean 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; } }
原文連結:https://blog.csdn.net/weixin_40816738/article/details/116646412