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

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

    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();
    

提交回复
热议问题