2012-11-06 24 views
2

如果我嘗試反序列化的json:GSON NumberFormatException的

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"

回答

6

你JSON是排在首位壞。你不應該把數字表示爲字符串。基本上,您的 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);