我想嘗試從Long Array中獲取Long
的值。但我有此異常:在線程從Java的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在運行時注入,而不是JSONArray jsonArray的龍 –
嘗試'整數的列表= jsonObject.getJSONArray(「department」); Collection depts = JSONArray.toCollection(jsonArray,List.class);'如果有幫助。還沒有嘗試過自己。這裏是'toCollection()'方法的JavaDoc:**返回一個列表或一個考慮泛型的集合** –
ujulu