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
This solution works for Double types. This will only work for non-primitive types:
public class DoubleGsonTypeAdapter implements JsonDeserializer {
@Override
public Double deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
Double result = null;
try {
result = jsonElement.getAsDouble();
} catch (NumberFormatException e) {
return result;
}
return result;
}
}
Model:
@SerializedName("rateOfInterest")
public Double rateOfInterest;
@SerializedName("repaymentTenure")
public Double repaymentTenure;
@SerializedName("emiAmount")
public Double emiAmount;
Retrofit client:
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new DoubleGsonTypeAdapter()) .create();
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();