Trying to achieve keep the 4 decimal point formatting when deserializing from json. Right now it only gets one decimal point e.g. 1800.0. This is the json string that needs deserializing:
{
"root": [
{
"paymentType": [
{
"listPrice": 1800.0000
}
]
}
]
}
I have these classes:
public class Root {
...
public List<Package> package;
}
And Package
public class Package {
...
public List<PaymentType> paymentType;
}
And PaymentType
public class PaymentType {
...
public Double listPrice;
}
I want to format the listPrice to keep it's four decimal point. It's truncated down to .0 now.
The gson serialization code:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<Double>() {}.getType(), new DoubleDeserializer());
Gson gson = gsonBuilder.create();
Root root = gson.fromJson(rawJson, Root.class);
DoubleDeserializer looks like:
public class DoubleDeserializer implements JsonDeserializer<Double> {
@Override
public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return json.getAsBigDecimal().setScale(4, RoundingMode.DOWN).doubleValue();
}
}
Seems to me that the serialization doesn't apply to nested objects, but I could be wrong. Do I need to create the deserializer for the PaymentType class and format the listPrice there?
Update: I tried deserialize PaymentType class instead:
public PaymentType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject paymentType = json.getAsJsonObject();
if (isValid(paymentType)) {
double listPrice = paymentType.get("listPrice").getAsDouble();
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ROOT);
df.applyPattern("#0.0000");
double formattedListPrice = Double.parseDouble(df.format(listPrice));
PaymentType formattedPaymentType = new PaymentType();
formattedPaymentType.listPrice = formattedListPrice;
return formattedPaymentType;
}
return new Gson().fromJson(json, PaymentType.class);
}
But getting the same results: 1800.0. This is due to the conversion done in the getAsDouble(), or any other parse method from json value 1800.0000. When the formatting is applied, the value is 1800.0 from the start, which makes the formatting redundant. Any tip how to combat this?
Final update: Solved (thanks @JoopEggen) by changing the Double type to BigDecimal type for listPrice in PaymentType and format using:
BigDecimal formattedListPrice =
paymentType.get("listPrice").getAsBigDecimal().setScale(4, RoundingMode.CEILING);
Thank you!