Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson.toJson(object) BigDecimal Precision Lost

Tags:

java

json

gson

When I converting Object to Json, I have a problem with BigDecimal Precision loosing.
Let Say I have Pojo Class with,

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

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

3rd Test - Wrong Output (Lost BigDecimal Precision)

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. What is the problem with json coversion. Would you please provide me the solution?

like image 257
Surendra Jnawali Avatar asked Oct 21 '22 12:10

Surendra Jnawali


1 Answers

I think your mixing Java EE 7's JSONObject with GSON's JsonObject. Gson doesn't seem to have the issue you mention:

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\"}"}
}
like image 143
Kevin Bowersox Avatar answered Oct 31 '22 14:10

Kevin Bowersox