簡體   English   中英

Gson NumberFormatException

[英]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:對於輸入字符串:“ 5,2”

如何解析“5,2”到Double ???

我知道如果我使用"floatImporte":"5.2"我可以毫無問題地解析它,但是我該解析"floatImporte":"5,2"

你的JSON首先是糟糕的。 您根本不應將數字表示為字符串。 你應該基本上要么都String在你的屬性ViewLineaAsiento的Java bean對象表示為好,或刪除其代表數字JSON性能的雙引號(並修復部分分隔成.而不是, )。

如果你想要繼續使用這個糟糕的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM