2014-03-14 195 views
5

當我將Object轉換爲Json時,BigDecimal Precision失去了一個問題。
讓說我有POJO類用,gson.toJson(object)BigDecimal精度丟失

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 coversions有什麼問題。你能否給我提供解決方案?

+0

是否缺少JEE 7'JSONObject'和'Gson'? –

+0

@fge對不起,我有這樣的輸出... –

回答

3

我想你的混合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\"}"} 
} 
+0

是的!來自net.sf.json.JSONObject的JSONObject; Bigdecimal問題...但是當我從org.json.simple.JSONObject使用沒有問題。爲什麼會發生?我在整個項目中使用Gson的JSONOBject –

+0

@SurendraJnawali它必須是'net.sf.json.JSONObject'的實現,我只需要使用Gson的'JsonObject'。 –

+0

謝謝你的解決方案! –