Is JsonElement integer or float?

Viewed 2824

Is it possible to determine whether a GSON JsonElement instance is an integer or is it a float?

I'm able to determine whether it's a number:

JsonElement value = ...
boolean isNumber = value.getAsJsonPrimitive().isNumber();

But how to determine if it's an integer or a float, so I can subsequently use the correct conversion method? Either

float f = value.getAsJsonPrimitive().getAsFloat();

or

int i = value.getAsJsonPrimitive().getAsInt();

Edit: The other question may answer why this may be not implemented in GSON, but this question definitely isn't its duplicate.

2 Answers

The only way I've found so far is using regex on a string:

if (value.getAsJsonPrimitive().isNumber()) {
    String num = value.getAsString();
    boolean isFloat = num.matches("[-+]?[0-9]*\\.[0-9]+");
    if (isFloat)
        System.out.println("FLOAT");
    else
        System.out.println("INTEGER");
}

This correctly determines 123 as integer, and both 123.45 and 123.0 as floats.

use something like, and so if return json object is an instance of float or integer you can then apply the required get:

JSONObject jObj = new JSONObject(jString);
Object aObj = jObj.get("a");
if(aObj instanceof Integer){
    System.out.println(aObj);
}
Related