Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert value from JsonObject to BigDecimal

I'm a newbiew in java language. I want to get a value from a JsonObject and convert it to BigDecimal. I have the following code:

JsonReader jsonReader;
try {
    jsonReader = Json.createReader(httpRequest.getReader());
} catch (IOException e) {
    return Response.serverError().entity("Problem reading json body").build();
}

JsonObject jsonObj = jsonReader.readObject();

Map<String, Object> paramMap = UtilMisc.toMap("productId", productId, "internalName",
        jsonObj.getString("internalName"), "productName", jsonObj.getString("productName"), "productTypeId",
        jsonObj.getString("productTypeId"), "login.username", username, "login.password", password,
        "description", jsonObj.getString("description"), "longDescription", jsonObj.getString("longDescription"),
           "productHeight", (BigDecimal)jsonObj.get("productHeight"));

What I want is to do something similar to (BigDecimal)jsonObj.get("productHeight").

Thank you.

like image 561
Ricardo Rocha Avatar asked Feb 13 '26 13:02

Ricardo Rocha


1 Answers

First, jsonObj.get is not a method, so surely that's the error.

Second, I don't think that casting any object to a BigDecimal is going to work like that.


Reading the API...

Going down from JsonReader to BigDecimal

JsonReader 
   > JsonObject
       > JsonNumber
          > BigDecimal 

You can do

jsonObj.getJsonNumber("productHeight").bigDecimalValue()

This assumes that productHeight is a numeric value, and not a string, though.

If it is a String, look at BigDecimal constructors. Specifically the one that takes a String value.

new BigDecimal(jsonObj.getString("productHeight"))
like image 195
OneCricketeer Avatar answered Feb 16 '26 03:02

OneCricketeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!