Convert value from JsonObject to BigDecimal

Ricardo Rocha picture Ricardo Rocha · Oct 12, 2016 · Viewed 8.3k times · Source

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.

Answer

OneCricketeer picture OneCricketeer · Oct 12, 2016

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"))