Skip to content
Advertisement

Long won’t convert to a string in java [closed]

I am trying to convert a long to an integer but nothing seems to work, the code snippet that wont work is ((int)jo.get("gold"))

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

Advertisement

Answer

Once we strip away the boxing and unboxing that Java is doing, here’s what you’re doing.

(java.lang.Integer)jo.get("hp")

where jo.get("hp") is an object whose runtime type is (evidently) java.lang.Long. Now, it looks like you’re harmlessly casting long to 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.

(long)(Integer)jo.get("hp")

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 .get return 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.

Advertisement