【发布时间】:2021-01-15 14:08:47
【问题描述】:
for(int i=0; i<roomsJSONArr.size(); i++){
JSONObject curRoom = (JSONObject) roomsJSONArr.get(i);
int test = (int) curRoom.get("id");
}
结果:
Exception in thread "main" java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.Integer (java.lang.Long and java.lang.Integer are in module java.base of loader 'bootstrap')
at rogue.Rogue.createRooms(Rogue.java:122)
at rogue.A1Solution.main(A1Solution.java:59)
首先:JSON 文件中的所有数字都解释为 Long 吗?
第二:为什么这不起作用?它在其他地方对我有用
编辑:为了更清楚,错误是在int test = (int) curRoom.get("id");引发的
【问题讨论】:
-
int test = (int) curRoom.get("id");行中是否抛出异常? -
@Hassan 是的,是的
-
尝试 ((Number) curRoom.get("id")).intValue() 或检查您的库是否有可以使用的 getInt 方法
-
这可能是溢出,它发生在 ID 中的 long 太大而无法保存在整数中时。您可以使用
Integer i = (Integer) Long.MAX_VALUE之类的东西在 jshell 上重现它。我无法使用int重现它,这就是我问上一个问题的原因。
标签: java json type-conversion