首先,實體類中的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 }