解決前后端交互Long類型精度丟失的問題
雪花算法ID,對應的后端Long類型,前端number類型,它們的精度不一樣,導致精度丟失
| 喜歡聽我叨叨的,直接看視頻 |
01
現(xiàn)象
雪花算法得到的ID較長,傳到前端后,精度丟失
庫中存的值:23754851322302474
后端取的值:23754851322302474
前端得到值:23754851322302470,數(shù)據(jù)被四舍五入了
02
解決方法
將Long類型轉(zhuǎn)成String,再傳給前端
方法一:單個注解
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
方法二:統(tǒng)一配置
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;
/**
* 統(tǒng)一注解,解決前后端交互Long類型精度丟失的問題
* 公眾號:甲蛙全棧
* 關(guān)聯(lián)視頻課程《Spring Boot + Vue3 前后端分離 實戰(zhàn)wiki知識庫系統(tǒng)》
* https://coding.imooc.com/class/474.html
* 示例網(wǎng)站:http://wiki.courseimooc.com
*/
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
—————— THE END ——————
掃碼關(guān)注,好文不錯過
評論
圖片
表情
