alterardm3 dm3
alterardm3 dm3

Reputation: 13

Trying to read Integer from JSON file in java

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

Upvotes: 0

Views: 4271

Answers (3)

AbGator
AbGator

Reputation: 59

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.

Upvotes: 0

that other guy
that other guy

Reputation: 123650

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

Upvotes: 3

Aify
Aify

Reputation: 3537

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);
}

Upvotes: 0

Related Questions