JSON - 简单得到一个Integer而不是Long [英] JSON - simple get an Integer instead of Long
问题描述
如何从JSON获取 Integer
而不是 Long
?
How to get an Integer
instead of Long
from JSON?
我想在我的Java程序中读取JSON,但是当我得到一个JSON值是一个数字时,我的解析器返回一些类型 Long
。
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
.
我想获得整数
。我试图将long转换为整数,但java抛出 ClassCastException
( java.lang.Long
无法转换到 java.lang.Integer
)。
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
).
我尝试了几件事,比如先把长号转换为字符串,然后使用 Integer.parseInt();
进行转换,但这也无效。
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.
我正在使用 json-simple
编辑:
我仍然无法正常工作。这是一个例子:
jsonItem.get(amount); //返回一个对象
I still can't get it working. Here is an example: jsonItem.get("amount"); // returns an Object
我可以这样做:
(long)jsonItem.get("amount");
但不是这样:
(int)jsonItem.get("amount");
我也无法将其转换为
Integer newInt = new Integer(jsonItem.get("amount"));
或
Integer newInt = new Integer((long)jsonItem.get("amount"));
推荐答案
请理解 Long
和 Integer
是对象类,而 long
和 int
是原始数据类型。您可以在后者之间自由施放(可能丢失高位),但您必须在前者之间进行实际转换。
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());
这篇关于JSON - 简单得到一个Integer而不是Long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!