Search code examples
javajsonparsingclasscastexceptionjson-simple

Parsing Json Numerical Values In Java


My Java program takes a JSON string as an argument and parses it. I am using json-simple parser. Here is the link to it. I am trying to pass the following JSON string as an argument to the program.

{
  "obj":"timeout" , 
  "valInMs":15000
}

I am trying to get the value for "valInMs" . Following is the java code that is doing this

JSONParser parser = new JSONParser();
JSONObject jsonObj;
jsonObj = (JSONObject) parser.parse(jsonString);
Integer timeout = (Integer) paramJson.get("valInMs");

The above code raises java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer .

I am trying to understand what should the program be expecting when it comes across a JSON numberic value. One cannot determine the "type" by looking at the JSON object.

How should a java program be handling this ?

Form json.org it seems like a Json "value" (out of many other things that it can be) can be "number" . A "number" can be one of the following:

number
 - int
 - int frac
 - int exp
 - int frac exp

Solution

  • Number timeoutNum = (Number) paramJson.get("valInMs");
    Long timeoutLong = null;
    Double timeoutDouble = null;
    if (timeoutNum instanceof Long) {
        timeoutLong = (Long) timeoutNum;
    }
    else if (timeoutNum instanceof Double) {
        timeoutDouble = (Double) timeoutNum;
    }
    else { ... punt ... }
    

    Or one can use intValue() et al on timeoutNum, if necessary coercing between integer and float.