美文网首页
Gson NumberFormatException

Gson NumberFormatException

作者: 莫问何昔 | 来源:发表于2018-05-07 13:38 被阅读0次
      private Retrofit createRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(buildGson()))
                .client(okHttpClient())
                .build();
    }
    
    private Gson buildGson() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Integer.class, new IntegerNullAdapter())
                .registerTypeAdapter(int.class, new IntegerNullAdapter())
                .create();
    
        return gson;
    }
    
    public class IntegerNullAdapter extends TypeAdapter<Integer> {
        @Override
        public Integer read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return 0;
            }
            String stringValue = reader.nextString();
    
            try{
                return Integer.valueOf(stringValue);
            }catch(NumberFormatException e){
                return null;
            }
        }
        @Override
        public void write(JsonWriter writer, Integer value) throws IOException {
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }
    }

    相关文章

      网友评论

          本文标题:Gson NumberFormatException

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