Gson NumberFormatException
gson, java, numberformatexception
Solution
Your JSON is in first place bad. You shouldn't be representing numbers as strings at all. You should basically either have all `String` properties in your `ViewLineaAsiento` Java bean object representation as well, or to remove those doublequotes from JSON properties which represent numbers (and fix the fraction separator to be `.` instead of `,`).
If you're absolutely posisive that you want to continue using this bad JSON and fix the problem by a workaround/hack instead of fixing the problem by its roots, then you'd need to create a custom Gson deserializer. Here's a kickoff example:
public static class BadDoubleDeserializer implements JsonDeserializer<Double> {
@Override
public Double deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException {
try {
return Double.parseDouble(element.getAsString().replace(',', '.'));
} catch (NumberFormatException e) {
throw new JsonParseException(e);
}
}
}
You can register it via `GsonBuilder#registerTypeAdapter()` as follows:
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new BadDoubleDeserializer()).create();
ViewLineaAsiento asiento = gson.fromJson(myjson, ViewLineaAsiento.class);
Problem
If I try to deserialize my json: ``` String myjson = " { "intIdfCuenta":"4720", "intIdfSubcuenta":"0", "floatImporte":"5,2", "strSigno":"D", "strIdfClave":"FT", "strDocumento":"1", "strDocumentoReferencia":"", "strAmpliacion":"", "strIdfTipoExtension":"IS", "id":"3" }"; viewLineaAsiento asiento = gson.fromJson(formpla.getViewlineaasiento(),viewLineaAsiento.class); ``` I get this error: com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "5,2" How can I parse "5,2" to Double??? I know that if I use `"floatImporte":"5.2"` I can parse it without any problem but I what to parse `"floatImporte":"5,2"`