5

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.

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • 2
    Possible duplicate of [How to prevent Gson from expressing integers as floats](https://stackoverflow.com/questions/15507997/how-to-prevent-gson-from-expressing-integers-as-floats) – lucidbrot Nov 13 '18 at 15:03
  • @lucidbrot I don't see how this is a duplicate. – Rok Povsic Nov 13 '18 at 15:09
  • quoting: "Since JSON doesn't distinguish between integer and floating point fields Gson has to default to Float/Double for numeric fields.". Sounds to me like exactly what you're asking about – lucidbrot Nov 13 '18 at 15:15
  • @lucidbrot I see this answer as being orthogonal to my question. Whatever the way Gson defaults numbers, there could be a way of it answering whether the number essentially "contains a dot" or not. – Rok Povsic Nov 13 '18 at 16:29
  • Okay, then great you've clarified that it's not a dupe – lucidbrot Nov 13 '18 at 16:33

2 Answers2

0

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.

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
-1

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);
}
Ptyler649
  • 69
  • 1
  • This does not work since `jObj.get("a")` returns `JsonElement` which is never `Integer` or `Float` (i.e. `Integer` is not a child of `JsonElement`). – Rok Povsic Nov 13 '18 at 16:41
  • This is a direct copy from [here](https://stackoverflow.com/a/15920281/3271729). At least link give credit to the original answer – Eamon Scullion Nov 13 '18 at 17:02
  • Additionally, this answer uses `org.json.simple.*` and not Gson. – Rok Povsic Nov 13 '18 at 17:14