如果我尝试反序列化我的 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);
我收到此错误:
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "5,2"
如何将“5,2”解析为 Double???
我知道如果我使用 "floatImporte":"5.2"
我可以毫无问题地解析它,但我要解析什么 "floatImporte":"5,2"
>
最佳答案
你的 JSON 首先是坏的。您根本不应该将数字表示为字符串。基本上,您应该在 ViewLineaAsiento
Java bean 对象表示中拥有所有 String
属性,或者从表示数字的 JSON 属性中删除那些双引号(并将分数分隔符修复为是 .
而不是 ,
)。
如果您绝对确定要继续使用这个糟糕的 JSON 并通过变通方法/黑客解决问题,而不是从根本上解决问题,那么您需要创建一个 custom Gson deserializer 。这是一个启动示例:
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);
}
}
}
您可以通过GsonBuilder#registerTypeAdapter()
注册它,如下所示:
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new BadDoubleDeserializer()).create();
ViewLineaAsiento asiento = gson.fromJson(myjson, ViewLineaAsiento.class);
关于java - Gson NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13253238/