如果我试图反序列化我的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:用于输入字符串:"5,2“
如何将"5,2“解析为”双倍“??
我知道如果我使用"floatImporte":"5.2",我可以没有任何问题地解析它,但是我要解析"floatImporte":"5,2"
发布于 2012-11-06 14:59:34
您的JSON是最糟糕的。你根本不应该把数字表示成字符串。基本上,您应该在JSON对象表示中包含所有String属性,或者从ViewLineaAsiento属性中删除那些表示数字的双引号(并将分数分隔符修正为.而不是,)。
如果您非常积极地希望继续使用这个糟糕的JSON,并通过解决办法/黑客来解决问题,而不是从根源上解决问题,那么您就需要创建一个自定义Gson反序列化器。下面是一个开球的例子:
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);https://stackoverflow.com/questions/13253238
复制相似问题