springboot中使用Long类型导致前端获取时精度丢失的问题
程序员文章站
2022-07-15 13:17:56
...
首先,实体类中的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
}