JSON - simple get an Integer instead of Long
Asked Answered
E

2

15

How to get an Integer instead of Long from JSON?

I want to read JSON in my Java program, but when I get a JSON value which is a number, my parser returns a number of type Long.

I want to get an Integer. I tried to cast the long to an integer, but java throws a ClassCastException (java.lang.Long cannot be cast to java.lang.Integer).

I tried several things, such as first converting the long to a string, and then converting with Integer.parseInt(); but also that doesn't work.

I am using json-simple

Edit:

I still can't get it working. Here is an example: jsonItem.get("amount"); // returns an Object

I can do this:

(long)jsonItem.get("amount");

But not this:

(int)jsonItem.get("amount");

I also can't convert it with

Integer newInt = new Integer(jsonItem.get("amount"));

or

Integer newInt = new Integer((long)jsonItem.get("amount"));
Elysha answered 1/1, 2014 at 13:32 Comment(4)
The Long object has an intValue() method.Grace
Now it looks like you are deliberately trying to come up with each possible variation on the right solution that is not right. Why don't you just follow the example provided to you by either Hot Licks or Joop Eggen?Laconic
I got it working. Thanks. I was confused by the classes and data typesElysha
Listen carefully: JSON is returning a Long object. That object contains within it a long value. If you want that value to be represented in an Integer object you must extract the value from the Long object and create a new Integer object from the value.Instrumentalist
I
9

Please understand that Long and Integer are object classes, while long and int are primitive data types. You can freely cast between the latter (with possible loss of high-order bits), but you must do an actual conversion between the former.

Integer newInt = new Integer(oldLong.intValue());
Instrumentalist answered 1/1, 2014 at 13:38 Comment(3)
Integer.valueOf(oldLong.intValue()) would be preferred, or the equivalent, but less explicit (int)(long)oldLong.Laconic
@MarkoTopolnik -- Yeah, that would be better.Instrumentalist
Per OP's first example, if the (long)jsonItem.get("amount"); can be parsed as a long, why not a primitive int?Staphylococcus
K
1

I tried

(int)(long)jsonItem.get("amount");  

and it worked for me

Kant answered 6/1, 2022 at 5:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.