I am trying to convert a long to an integer but nothing seems to work, the code snippet that wont work is
The full line of code is
gamePlayer = new Player(((double) jo.get("hp")), ((double) jo.get("maxHp")), ((int) jo.get("gold")), true, jo.get("name").toString());
Once we strip away the boxing and unboxing that Java is doing, here’s what you’re doing.
jo.get("hp") is an object whose runtime type is (evidently)
java.lang.Long. Now, it looks like you’re harmlessly casting
int, but that’s because it’s all hidden behind autoboxing. In reality, you’re casting an
Object which is not an
Integer into an
Integer. It has nothing to do with the numerical types; this is just an invalid downcast.
To fix the immediate problem, you need to cast to the correct runtime type first and then let autoboxing take it from there.
I can’t find very much documentation on the
org.json.simple.JSONObject class you’re using, but my guess is that it’s poorly written and has
Object, hence your confusion. Java has official JSON support built-in, so I recommend using that class. It’s strongly typed and will do the type checking for you better than the library you’re using now seems to be.