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

后端 未结 7 647
情深已故
情深已故 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:07

    I've made this TypeAdapter which check for empty strings and return 0

    public class IntegerTypeAdapter extends TypeAdapter {
    @Override
    public void write(JsonWriter jsonWriter, Number number) throws IOException {
        if (number == null) {
            jsonWriter.nullValue();
            return;
        }
        jsonWriter.value(number);
    }
    
    @Override
    public Number read(JsonReader jsonReader) throws IOException {
        if (jsonReader.peek() == JsonToken.NULL) {
            jsonReader.nextNull();
            return null;
        }
    
        try {
            String value = jsonReader.nextString();
            if ("".equals(value)) {
                return 0;
            }
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }
    

    }

提交回复
热议问题