Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON - simple get an Integer instead of Long

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"));
like image 750
user2190492 Avatar asked Jan 01 '14 13:01

user2190492


People also ask

Does JSON support long?

As a practical matter, Javascript integers are limited to about 2^53 (there are no integers; just IEEE floats). But the JSON spec is quite clear that JSON numbers are unlimited size.

Can JSON return integer?

Strictly speaking, json is untyped, so you can't send it as an integer, it has to be a string.

Does ordering matter in JSON?

The JSON RFC (RFC 4627) says that order of object members does not matter.


1 Answers

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());
like image 51
Hot Licks Avatar answered Oct 27 '22 12:10

Hot Licks