Search code examples
javaandroidjsonretrofitretrofit2

Retrofit - How to error handle the NumberFormatException in retrofit?


I use retrofit to implement an interface like this:

Observable<QueryResult> queryData(@Body QueryParams params);

and define the QueryResult class:

class QueryResult {
    int count;
    ...
}

When I execute the queryData statement, it produces the following error:

com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""

Apparently, it is caused by the api returning data something like this:

{"count":"",...}

The "count" is designed to represent a number, but somehow or maybe sometimes, the server developer wants to use "" to represent 0.

My question is how do I error handle this situation?

I have tried to do the error handling in the QueryResult class:

class QueryResult {
    String count; // change from int to String;
    ...
    int getCount() {
        // do the error handling
        int ret = 0;
        try {
            ret = Integer.parseInt(count);
        } catch (Exception e) {}
        return ret;
    }
}

But is there a better way of handling it? Declaring the count to be a String seems not quite intuitive. I am supposing there could be an option to configure the retrofit.

Update Thanks for the answers of suggestions for efficiency improvement and registering a TypeAdapter in the gson converter. But what I want to know is if the error handle could be done by the retrofit library itself. The point of view is that when I originally declare the count field as int, it can handle both the integer and string type of value from server, like:

{"count":123,...} or {"count":"123",...}

without error. So I am assuming the error handle could be done together with the integer paring behavior in the library itself.

Thanks in advance.


Solution

  • First of all this inconsistent behaviour in API response is not feasible. Retrofit won't be able to handle this situation.You have to manually handle this response as you have mentioned in the question.But you can do that in an efficient way like this

    class QueryResult {
    
            Object count; // change to Object;
    
            int getCount() {
                // do the error handling
                if (count instanceof Integer) {
                    return ((Integer) count);
                } else {
                    return 0;
                }
            }
        }