0

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
2
  • It is quite unfortunate that JSON-Simple (apparently) lacks any sort of rigorous documentation. Commented Oct 2, 2014 at 18:30
  • I haven't tried it, but I think you can use int timeout = Integer.parseInt(paramJson.get("valInMs").toString()); Commented Oct 2, 2014 at 18:32

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0
// This works for me

if (jobj.get("valInMs") != null)
{
    Number val = (Number) jobj.get("valInMs");
    int valInMs = val.intValue();
}
else
    valInMs = 0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.