java - Gson NumberFormatException

标签 java gson numberformatexception

如果我尝试反序列化我的 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/

相关文章:

java - token "try"出现语法错误,请删除此 token

java - JAXB - 如何使用 <set varname = "String"value = name "String2"> 元素从对象创建 xml

java - 如何解码这个嵌套的 JSON 字符串?

java - gson反序列化: Reference owner of nested object

java - 使用 Integer.parseInt 转换 32 位二进制字符串失败

java - 当我在模拟器中打开此 Activity 时,我收到 NumberFormatException 和 NullPointerException。为什么?

java - 来自十六进制数的 NumberFormatException

java - 准备好的语句和串行数据类型

java - 使用阿拉伯字符创建 zip 文件

java - Gson 的 .toJson 方法将 < 替换为\u003c