Reputation: 13
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
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
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:
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
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