This question already has answers here:
Closed 2 years ago.
I'm using some API by restTemplate. The API returns a key whose type is integer.
But I'm not sure of that value, so I want to check whether the key is really an integer or not.
I think it might be a string.
What is the best way of checking if the value is really integer?
added:
I mean that some API might return value like below.
{id : 10} or {id : "10"}
Object x = someApi();
if (x instanceof Integer)
Note that if someApi()
returns type Integer
the only possibilities of something returned are:
In which case you can:
if (x == null) {
// not an Integer
} else {
// yes an Integer
}
If what you receive is a String, you can try to parse it into an integer, if it fails, it's because it was not an integer after all. Something like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
One possibility is to use Integer.valueOf(String)
Assuming your API return value can either be an Integer or String you can do something like this:
Integer getValue(Object valueFromAPI){
return (valueFromAPI != null ? Integer.valueOf(valueFromAPI.toString()) : null);
}