【发布时间】:2016-04-10 16:59:33
【问题描述】:
我想尝试从 Long Array 中获取 Long 值。但我有这个例外:
线程“主”java.lang.ClassCastException 中的异常: java.lang.Integer 不能转换为 java.lang.Long
这样的代码:
import java.util.List;
public class Bar {
private List<Long> departments;
public List<Long> getDepartments() {
return departments;
}
public void setDepartments(List<Long> departments) {
this.departments = departments;
}
}
import java.util.List;
import net.sf.json.JSONObject;
public class Foo {
public static void main(String[] args) {
String str = "{\"departments\":[20,22]}";
JSONObject jsonObject = JSONObject.fromObject(str);
Bar bar = (Bar) jsonObject.toBean(jsonObject, Bar.class);
List<Long> departments = bar.getDepartments();
Long depId = departments.get(0);// Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
System.out.println(depId);
}
}
【问题讨论】:
-
可能是因为 jsonObject.toBean 在运行时注入了一个 Integer 列表而不是 Long
-
如果有帮助,请尝试
JSONArray jsonArray = jsonObject.getJSONArray("department"); Collection<Long> depts = JSONArray.toCollection(jsonArray, List.class);。自己没试过。以下是toCollection()方法的 JavaDoc:考虑泛型返回一个 List 或一个 Set。
标签: java