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
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.