3

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"}

gentlejo
  • 2,690
  • 4
  • 26
  • 31

4 Answers4

11

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;
    }
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
9
Object x = someApi();

if (x instanceof Integer) 

Note that if someApi() returns type Integer the only possibilities of something returned are:

  • an Integer
  • null

In which case you can:

if (x == null) {
    // not an Integer
} else {
    // yes an Integer
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

One possibility is to use Integer.valueOf(String)

Raghuram
  • 51,854
  • 11
  • 110
  • 122
  • This assumes the object is a string. What if it's *actually* an Integer? This is where I don't understand the OP's question: they ask as if the return type is unknown (and unknowable) – NullUserException Dec 01 '11 at 04:46
0

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); 
}
mprabhat
  • 20,107
  • 7
  • 46
  • 63