0

I am trying to read a JSON file to create a new Object. I can read all the Strings in it but i throws a ClassCastException when trying to read an int. Here is the JSON file.

{"id1" : "string1", 
 "id2": "string2",            
 "id3": 100.0
}   

And here is the java code.

public static Aparelho novoAparelho(JSONObject obj) {

    Aparelho ap = null;

        String tipe = (String) obj.get("id1");
        String name = (String) obj.get("id2");


        if(tipe.equals("anyString")) {
            int pot = (int) obj.get("id3");
            ap = new SomeObject(name, pot);
        }

    return ap;
}

It throws. Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

3 Answers 3

3

Cast it to double first:

int pot = (int) (double) obj.get("id3");
ap = new SomeObject(name, pot);

Confusingly, there are three kinds of casts:

  • Those that convert values of primitives
  • Those that change the type of a reference
  • Those that box and unbox

In this case, you have an Object (which is actually a boxed Double), and you want a primitive int. You can't unbox and convert with the same cast, so we need two casts: first from Object to double (unboxing), and one from double to int (conversion).

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

Comments

0

Integers don't have decimal points.

You should be parsing for an int instead of casting as an int.

For example:

if (tipe.equals("anyString")) {
    String pot = obj.get("id3");
    int x = Integer.parseInt(pot);
    ap = new SomeObject(name, x);
}

2 Comments

if i remove the decimal poit the exception is Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
@alterardm3dm3 Do it using the cast method in my answer.
0

Since you know that the field is supposed to be an int, you can take advantage of the JSONObject api to handle the parsing for you:

        if(tipe.equals("anyString")) {
            int pot = obj.getInt("id3");
            ap = new SomeObject(name, pot);
        }

This is a bit more robust than the casting method -- if somebody changes the json that gets passed to you, the accepted answer might break.

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.