【发布时间】:2015-04-21 11:00:52
【问题描述】:
我在 REST 服务中解析 JSON 整数时遇到问题。解析字符串和双精度类型工作正常
工作:
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");
不工作:
int baskId = (Integer) jsonObject.get("basketId");
我尝试将我的购物篮类中的basketId 转换为字符串,然后它运行正常,所以代码正常,并且链接工作,但是,当我将它转换回 int 时,我得到 500 服务器错误。我正在使用它来创建一个带有一些数字 ID 的新篮子,因此我使用了 @POST 注释,并且负载中的 JSON 如下:
{"basketId":50}
我不明白...
编辑: 我明白了...JSON simple 只接受更大类型的 Java 原语,所以整数和浮点数是不行的
【问题讨论】:
-
什么是错误信息?
-
你使用什么库?它没有
getInt(...)方法吗? -
它的JSON简单库,code.google.com/p/json-simple,没有getInt,直接get。双被解析得很好。我正在使用 chrome rest 客户端插件,所以我收到 500 内部服务器错误。 eclipse没有错误
-
Integer.parseInt()..stackoverflow.com/questions/15699953/…
-
在这种情况下,您必须在转换之前检查值
basketId的类型。你可以使用instanceof或jsonObject.get("basketId").getClass()