简体   繁体   English

gson.toJson(对象)BigDecimal Precision Lost

[英]gson.toJson(object) BigDecimal Precision Lost

When I converting Object to Json, I have a problem with BigDecimal Precision loosing. 当我将Object转换为Json时,我遇到了BigDecimal Precision丢失的问题。
Let Say I have Pojo Class with, 让我说我有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;
    }
} 

Now I am setting value to Pojo then converting to JSON 现在我正在为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);
    }

1st Test - Correct Output 第一次测试 - 正确输出

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

2nd Test - Wrong Output (Lost BigDecimal Precision) 第二次测试 - 输出错误(丢失BigDecimal精度)

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

3rd Test - Wrong Output (Lost BigDecimal Precision) 第3次测试 - 输出错误(丢失BigDecimal精度)

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

Amazing that whenever BigDecimal value is higher length then it truncate decimal place as well. 令人惊讶的是,每当BigDecimal值更长时,它也会截断小数位。 What is the problem with json coversion. json coversion有什么问题。 Would you please provide me the solution? 你能帮我解决一下吗?

I think your mixing Java EE 7's JSONObject with GSON's JsonObject . 我认为你将Java EE 7的JSONObject与GSON的JsonObject混合在一起。 Gson doesn't seem to have the issue you mention: 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\"}"}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM