美文网首页
gson java.lang.NumberFormatExcep

gson java.lang.NumberFormatExcep

作者: 风___________ | 来源:发表于2019-02-12 19:50 被阅读6次

    标题:

    gson 序列化model 闪退

    错误信息:

    java.lang.NumberFormatException: empty String

    错误原因:

    类型不统一,gson 后台 string 转 int时,“” 导致崩溃
    eg:

    {
       "name" : "Test1",
       "business_type" : "90"
    }
    {
       "name" : "Test1",
       "business_type" : ""
    }
        @SerializedName("business_type")
        int businessType;
    

    解决方案:

    Gson gson = new Gson();
    

    替换为

    private Gson gson = new GsonBuilder()
                .registerTypeAdapter(int.class, new IntTypeAdapter())
                .registerTypeAdapter(Integer.class, new IntTypeAdapter()).create();
    

    工具类如下

    
    class IntTypeAdapter extends TypeAdapter<Number> {
    
        @Override
        public void write(JsonWriter out, Number value)
                throws IOException {
            out.value(value);
        }
    
        @Override
        public Number read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            try {
                String result = in.nextString();
                if ("".equals(result)) {
                    return null;
                }
                return Integer.parseInt(result);
            } catch (NumberFormatException e) {
                throw new JsonSyntaxException(e);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:gson java.lang.NumberFormatExcep

          本文链接:https://www.haomeiwen.com/subject/xytleqtx.html