The data returned from my application API contains the product price stored as a String for example:
{
price:"1500"
}
This causes a NumberFormatException because the data type used in the Product model is a BigDecimal. How do I parse this string from the database into a BigDecimal before using it within the application?
I am using Retrofit and GSON, and have tried the solutions here:
NumberFormatException in GSON when converting String to double
Solution 1:
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(Float.class, new TypeAdapter<Float>() {
@Override
public Float read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String stringValue = reader.nextString();
try {
Float value = Float.valueOf(stringValue);
return value;
} catch (NumberFormatException e) {
return null;
}
}
@Override
public void write(JsonWriter writer, Float value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(value);
}
});
This solution seems correct but I failed to return the parsed value when the exception occurs, instead of returning null.
Solution 2:
.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
public JsonElement serialize(Double number, Type type, JsonSerializationContext context) {
return new JsonPrimitive(Double.valueOf(number));
}
})
For this solution, BigDecimal isn't a supported JsonPrimitive datatype.