Java中Object可以直接轉成List實體類:
Map<String, List<Student>> mapIdAndStudent = new HashMap<>();
List<Student> studentList = new ArrayList<>();
mapIdAndStudent.put("c001", studentList);
// 直接轉換
List<Student> newStudentList = (List<Student>)mapIdAndStudent.get("c001");
通過這樣的方式,編譯和運行是沒有錯誤的,但是如果遍歷轉換以後的List就會報異常(java.util.LinkedHashMap cannot be cast to JavaBean)
解決方案:
我們需要把這個Object對象轉出字符串,然後再把字符串轉換成List<XXX>對象:
import com.alibaba.fastjson.JSONObject;
List<Student> newStudentList = JSONObject.parseArray(JSONObject.toJSONString(mapIdAndStudent.get("c001")), Student.class);
PS:親測有效。