How to handle a NumberFormatException with Gson in deserialization a JSON response

后端 未结 7 619
情深已故
情深已故 2020-12-01 03:45

I\'m reading a JSON response with Gson, which returns somtimes a NumberFormatException because an expected int value is set to an empty string. Now

7条回答
  •  無奈伤痛
    2020-12-01 04:03

    Here is example I did for Long type.This is better option:

        public class LongTypeAdapter extends TypeAdapter{
        @Override
        public Long read(JsonReader reader) throws IOException {
            if(reader.peek() == JsonToken.NULL){
                reader.nextNull();
                return null;
            }
            String stringValue = reader.nextString();
            try{
                Long value = Long.valueOf(stringValue);
                return value;
            }catch(NumberFormatException e){
                return null;
            }
        }
        @Override
        public void write(JsonWriter writer, Long value) throws IOException {
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }
    }
    

    Register the adapter upon creation of the gson util:

    Gson gson = new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()).create();
    

    You can refer to this link for more.

提交回复
热议问题