在json字符串轉java bean時,通常的對象,能夠直接轉,如:一個學生類,屬性有姓名、年齡等java
public class Student{ private String sname; private Integer age; public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
由字符串轉java bean時能夠使用如下方法:json
JSONObject jobj = JSONObject.fromObject(str); Student s = (Student) JSONObject.tobean(jobj,Student.class);
是沒有問題的,可是若是屬性中含有複雜的類型,當其中屬性有相似List , Map ,ArrayList、自定義的類型,如List<Teacher> teachers, 就不能夠了。 會報錯:MorphDynaBean cannot be cast to con.test……this
在JSONObject.toBean的時候若是轉換的類中有集合,能夠先定義Map<String, Class> classMap = new HashMap<String, Class>();在classMap中put你要轉換的類中的集合名,像:classMap.put("teachers", Teacher.class);而後在toBean()的時候把參數加上, 像:Student student=(Student) JSONObject.toBean(str, Student.class, classMap);spa
好比我定義了以下類型:code
import java.util.List; public class AnalysisModel{ /** * 固定條件 */ private List<Condition> regularCondtionList;// /** * 動態條件 */ private List<ConditionField> dynamicConFieldList; /** * 結果 */ private List<ResultField> resultField; /** * 獲取前多少條數據 */ private Integer topnum; /** * 順序仍是隨機 */ private String sortFlag; /** * 備註 */ private String remark; /** * 模型名稱 */ private String modelName; /** * 對應的xml文件名稱 */ private String fileName; public List<Condition> getRegularCondtionList() { return regularCondtionList; } public void setRegularCondtionList(List<Condition> regularCondtionList) { this.regularCondtionList = regularCondtionList; } public List<ConditionField> getDynamicConFieldList() { return dynamicConFieldList; } public void setDynamicConFieldList(List<ConditionField> dynamicConFieldList) { this.dynamicConFieldList = dynamicConFieldList; } public Integer getTopnum() { return topnum; } public void setTopnum(Integer topnum) { this.topnum = topnum; } public String getSortFlag() { return sortFlag; } public void setSortFlag(String sortFlag) { this.sortFlag = sortFlag; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public List<ResultField> getResultField() { return resultField; } public void setResultField(List<ResultField> resultField) { this.resultField = resultField; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
在轉化的時候須要這樣來寫:xml
Map<String, Class> classMap = new HashMap<String, Class>(); classMap.put("regularCondtionList", Condition.class); classMap.put("dynamicConFieldList", ConditionField.class); classMap.put("resultField", ResultField.class); AnalysisModel analysisModel=(AnalysisModel) JSONObject.toBean(str, AnalysisModel.class, classMap);