springboot中使用long型別導致前端獲取時精度丟失的問題
阿新 • • 發佈:2021-08-03
首先,實體類中的ID型別為LONG
前端接收到的ID精度丟失
{
"success": true,
"code": "200",
"data": [
{
"id": 1199222178982396000, //這裡精度丟失了!!
"idCard": "422202199910210811",
"personName": "string",
"age": 0,
}
],
"errorMessage": null,
"currentTime": "2019-11-26T07:06:25.301+0000"
}
但是資料庫中的ID是正常的
原因:JS中沒有長整型的型別,所以我們返回時應該轉化為字串型別
解決方案(SPRING BOOT版)
我這裡使用的fastjson進行序列化
使用MAVEN引入FASTJSON的依賴
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
FASTJSON的配置類
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
/**
* @Classname JsonConfig
* @Date 2019/11/26 15:16
* @Created by ChuWanJiang
*/
@Configuration
public class JsonConfig {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1.定義一個converters轉換訊息的物件
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2.新增fastjson的配置資訊,比如: 是否需要格式化返回的json資料
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3.在converter中新增配置資訊
fastConverter.setFastJsonConfig(fastJsonConfig);
// 4.將converter賦值給HttpMessageConverter
HttpMessageConverter<?> converter = fastConverter;
// 5.返回HttpMessageConverters物件
return new HttpMessageConverters(converter);
}
}
最後在實體類中加上註解
@ApiModelProperty(value = "id")
@JSONField(serializeUsing = ToStringSerializer.class)
@TableId(value = "id", type = IdType.ID_WORKER)
private Long id;
其中,引入的類為
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.ToStringSerializer;
大功告成
{
"code": "200",
"currentTime": 1574752655889,
"data": [
{
"age": 0,
"id": "1199225233215705089",
"idCard": "422202199910210811",
"personName": "string"
}
],
"success": true
}