java - gson.toJson(object) BigDecimal 精度丢失

标签 java gson json

当我将 Object 转换为 Json 时,我遇到了 BigDecimal 精度丢失的问题。
假设我有 Pojo 类,

public class DummyPojo {
    private BigDecimal amount;
    private String id;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public BigDecimal getAmount() {
        return amount;
    }
    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }
} 

现在我将值设置为 Pojo 然后转换为 JSON

public static void main(String[] args) {
        BigDecimal big = new BigDecimal("1000.0005");
        JSONObject resultJson = new JSONObject();
        DummyPojo summary = new DummyPojo();
        summary.setId("A001");
        summary.setAmount(big);

        resultJson.put("summary",new Gson().toJson(summary));
        String result = resultJson.toString();
        System.out.println(result);
    }

第一次测试 - 正确输出

Output -> {"summary":{"amount":1000.0005,"id":"A001"}}

第二次测试 - 错误输出(丢失 BigDecimal 精度)

BigDecimal big = new BigDecimal("1234567.5555"); //Changed the value
Output -> {"summary":{"amount":1234567.5,"id":"A001"}}

第三次测试 - 错误输出(丢失 BigDecimal 精度)

BigDecimal big = new BigDecimal("100000.0005"); //Changed the value
Output -> {"summary":{"amount":100000,"id":"A001"}}

令人惊奇的是,只要 BigDecimal 值的长度更长,它也会截断小数位。 json coversion有什么问题。你能给我解决方案吗?

最佳答案

我认为您将 Java EE 7 的 JSONObject 与 GSON 的 JsonObject 混合在一起。 Gson 似乎没有你提到的问题:

public static void main(String[] args) {
    BigDecimal big = new BigDecimal("1234567.5555");
    DummyPojo summary = new DummyPojo();
    JsonObject resultJson = new JsonObject(); //this is Gson not Java EE 7
    summary.setId("A001");
    summary.setAmount(big);
    resultJson.addProperty("summary", new Gson().toJson(summary));
    System.out.println(resultJson.toString());
    //Outputs: {"summary":"{\"amount\":1234567.5555,\"id\":\"A001\"}"}
}

关于java - gson.toJson(object) BigDecimal 精度丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22400470/

相关文章:

java - 如何将 FloatingActionButton 放到 Fragment 中?

java - 为什么我要扩展 java.lang.RuntimeException

java - 如何在不调用直接父级的情况下解析 HTML

android - 反序列化Gson中的有序列表

android - Gson 错误 JellyBean

.net - Azure API 应用程序 (.NET Core) 截断了大型 JSON 响应

java - onStartLoading() 和forceLoad() 是在哪里调用和实现的?

android - 如何迭代 JsonReader 两次?

javascript - 如何将 json 对象插入 Google 图表线

java - 如何在不中断 log4j2 的情况下在 Json 对象中记录异常堆栈跟踪