简体   繁体   中英

Convert mongo decimal number to java BigDecimal

I'm performing a Mongo query. My results contain decimalnumber data. How can I set my cost data in a java DecimalNumber attribute?

{ 
  "macroType" : "LIBRI", 
  "costType" : { 
     "$numberDecimal" : "4.60" 
  }, 
  "count" : 3 
}

It's a document that I add in a List. In the code below ai is my list.

I want to set costType in the BigDecimal attribute


Now I don't know how can do it. Thanks in advance.

for (int i = 0; i < ai.size(); i++) {
  String json = new GsonBuilder().create().toJson(ai.get(i));
  JsonElement je = new com.google.gson.JsonParser().parse(json);
  JsonObject root = je.getAsJsonObject();
  JsonElement je2 = root.get("costType");
}  

After fetching data from database in the document, You can convert numberDecimal field into the BigDecimal by...

BigDecimal cost = new BigDecimal(document.get("costType",Document.class).getString("$numberDecimal"));

System.out.print(cost);
System.out.println(cost.getClass());

O/p: 4.60 class java.math.BigDecimal

Old question but this might help someone. You can just use org.bson.json.JsonWriterSetting like so:

JsonWriterSettings settings = JsonWriterSettings.builder()
    .decimal128Converter(new Converter<Decimal128>() {
        @Override
        void convert(Decimal128 value, StrictJsonWriter writer) {
            writer.writeNumber(value.toBigDecimal().toPlainString())
        }
    })
    .build();

yourDocument.toJson(settings); // org.bson.Document

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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