java JSON 简单:整数解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29770329/
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: integer parsing
提问by Norgul
I have a problem parsing JSON integer in my REST service. Parsing String and double type works fine
我在 REST 服务中解析 JSON 整数时遇到问题。解析 String 和 double 类型工作正常
Working:
在职的:
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
//---------------
String uName = (String) jsonObject.get("userName");
double iPrice = (Double) jsonObject.get("itemPrice");
Not working:
不工作:
int baskId = (Integer) jsonObject.get("basketId");
I tried to convert the basketId
in my basket class to String, and then it functions ok, so code is okay, and link is working, however, when I cast it back to int, I get 500 server error. I am using it to create a new basket with some numeric ID, so I use the @POST annotation and the JSON in the payload is as follows:
我尝试将basketId
篮子类中的转换为字符串,然后它运行正常,所以代码正常,链接正常工作,但是,当我将其转换回 int 时,出现 500 服务器错误。我使用它来创建一个带有一些数字 ID 的新篮子,所以我使用了 @POST 注释,并且有效负载中的 JSON 如下:
{"basketId":50}
I don't get it...
我不明白...
EDIT: I do get it...JSON simple accepts just bigger types of Java primitives, so integer and float are a no-no
编辑:我明白了……JSON simple 只接受更大类型的 Java 原语,所以整数和浮点数是禁忌
回答by raki
In your code jsonObject.get("basketId");
returns Long
在您的代码中jsonObject.get("basketId");
返回 Long
So using Long for type casting would help you in resolving your error
(Long)jsonObject.get("basketId");
因此,使用 Long 进行类型转换将帮助您解决错误
(Long)jsonObject.get("basketId");
If you really need Integer then type cast it to inetger as follows
如果您确实需要 Integer ,则按如下方式将其强制转换为 inetger
((Long)jsonObject.get("basketId")).intValue()
回答by libik
If you parse it as String, you cant do something like this :
如果将其解析为字符串,则不能执行以下操作:
String x = "10";
int y = (int) x;
But you can use this method
但是你可以用这个方法
String x = "10";
int y = Integer.valueOf(x);
回答by Santo
Rather than : int baskId = (Integer) jsonObject.get("basketId");
而不是:int baskId = (Integer) jsonObject.get("basketId");
Use : int baskId = jsonObject.getInt("basketId");
使用:int baskId = jsonObject.getInt("basketId");
It is in the official documentation : http://www.json.org/javadoc/org/json/JSONObject.html#getInt(java.lang.String)
它在官方文档中:http: //www.json.org/javadoc/org/json/JSONObject.html#getInt(java.lang.String)