Java toJson(对象)BigDecimal精度丢失
当我将对象转换为Json时,我遇到了BigDecimal精度丢失的问题。Java toJson(对象)BigDecimal精度丢失,java,json,gson,jsonobject,Java,Json,Gson,Jsonobject,当我将对象转换为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; }
比如说,我有一节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 big = new BigDecimal("100000.0005"); //Changed the value
Output -> {"summary":{"amount":100000,"id":"A001"}}
第三次测试-输出错误(失去了BigDecimal精度)
BigDecimal big = new BigDecimal("1234567.5555"); //Changed the value
Output -> {"summary":{"amount":1234567.5,"id":"A001"}}
BigDecimal big = new BigDecimal("100000.0005"); //Changed the value
Output -> {"summary":{"amount":100000,"id":"A001"}}
令人惊讶的是,每当BigDecimal值的长度更大时,它也会截断小数位。
json转换有什么问题。你能给我提供解决方案吗 我认为您将JavaEE7与GSON混合使用。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\"}"}
}
您是否缺少JEE 7
JSONObject
和Gson
?@fge抱歉,我有这样的输出…是的!!!net.sf.json.JSONObject中的JSONObject;Bigdecimal问题…但当我使用from org.json.simple.JSONObject时,没有问题。为什么会这样?我使用的是Gson的JSONOBjectproject@SurendraJnawali它必须是net.sf.json.JSONObject
的实现,我将使用Gson的JSONObject
。