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.
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;
}
}
}
Try to check that your count
is empty or not before converting it to it
or better to change the response from backend
Try this
public class QueryResult {
String count;
int getCount() {
try {
if (!TextUtils.isEmpty(count)) {
return Integer.parseInt(count);
}
} catch (NumberFormatException e) {
}
return 0;
}
}
The sweetest way I can tell you is just parse double as way you do.
Double ans=Double.ParseDouble(yourstringvalue);
This gives ans as double.
The problem I get here is that you are receiving an empty string ""
Just put the condition on it as
Double ans=0.0
if(yourstringvalue!="" || yourstringvalue!=null){
// then parse here
ans=Double.ParseDouble(yourstringvalue);
}
You will get required value in ans
Proceed further as
if(ans!=0.0){
//do your task here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With