【问题标题】:Can't convert JSON result type无法转换 JSON 结果类型
【发布时间】: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


【解决方案1】:

试试int test = curRoom.get("id").intValue(),而不是int test = (int) curRoom.get("id")。如果这不起作用,那么正如 Hassan 在 cmets 中所说,它可能是整数溢出。如果是这种情况,那么您可以使用 BigInteger。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2019-09-30
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多