Java JSONArray 中 Long 类型 ID 精度丢失问题及解决方法
问题描述:
在 Java 中使用 JSONArray 存储数据,其中包含一个 id 字段,该字段类型为 long。当将 JSONArray 返回前端时,id 字段的精度发生了丢失。
解决方案:
JSON 数据格式中 long 类型的精度会发生丢失,因为 JSON 数据格式中的数值类型只支持 32 位精度,而 Java 中的 long 类型是 64 位精度。为了解决这个问题,可以将 id 字段转换为 String 类型再返回前端,或者使用 BigDecimal 类型代替 long 类型。
示例代码:
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
long id = 1234567890123456789L;
jsonObject.put('id', String.valueOf(id));
jsonObject.put('name', 'John');
jsonArray.put(jsonObject);
return jsonArray.toString();
在上面的示例中,将 id 字段转换为 String 类型之后再放入 JSONObject 中,然后将 JSONArray 转换为字符串返回前端。这样就能保证 id 字段的精度不会丢失。
另外,如果需要进行数值计算,可以使用 BigDecimal 类型代替 long 类型。示例代码如下:
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
BigDecimal id = new BigDecimal('1234567890123456789');
jsonObject.put('id', id);
jsonObject.put('name', 'John');
jsonArray.put(jsonObject);
return jsonArray.toString();
在上面的示例中,使用 BigDecimal 类型代替了 long 类型,并将 id 字段放入 JSONObject 中,然后将 JSONArray 转换为字符串返回前端。这样就能保证 id 字段的精度不会丢失,并且可以进行数值计算。
原文地址: https://www.cveoy.top/t/topic/nqif 著作权归作者所有。请勿转载和采集!