Java JSON - 简单地得到一个整数而不是长整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20869138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON - simple get an Integer instead of Long
提问by user2190492
How to get an Integerinstead of Longfrom JSON?
如何从 JSON获取Integer而不是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.
我想在我的 Java 程序中读取 JSON,但是当我得到一个数字的 JSON 值时,我的解析器返回一个类型的数字Long。
I want to get an Integer. I tried to cast the long to an integer, but java throws a ClassCastException(java.lang.Longcannot be cast to java.lang.Integer).
我想得到一个Integer. 我试图将 long 转换为整数,但 java 抛出一个ClassCastException(java.lang.Long不能转换为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.
我尝试了几种方法,例如首先将 long 转换为字符串,然后使用 with 进行转换,Integer.parseInt();但这也不起作用。
I am using json-simple
我正在使用json-simple
Edit:
编辑:
I still can't get it working. Here is an example: jsonItem.get("amount"); // returns an Object
我仍然无法让它工作。下面是一个例子: jsonItem.get("amount"); // 返回一个对象
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"));
采纳答案by Hot Licks
Please understand that Longand Integerare object classes, while longand intare 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.
请理解Long和Integer是对象类,而long和int是原始数据类型。您可以在后者之间自由转换(可能会丢失高位),但您必须在前者之间进行实际转换。
Integer newInt = new Integer(oldLong.intValue());

