JSON字符串转javabean,MorphDynaBean cannot be cast to...
如果碰到上面的问题,就是复杂对象没有正常转换,这个时候,你就要使用classMap.put("report_list", FlowStatistics.class); 这样的配置参数,如下代码:
对象信息:
public class FlowReport {
private List<FlowStatistics> report_list;
public List<FlowStatistics> getReport_list() {
return report_list;
}
public void setReport_list(List<FlowStatistics> report_list) {
this.report_list = report_list;
}
}
public class FlowStatistics {
private String sip;
public void setSip(String sip) {
this.sip = sip;
}
public String getDip() {
return dip;
}
}
测试代码:
String tmp = "{\"report_list\":"+ "[{\"sip\":\"10.0.0.1\"},"+ "{\"sip\":\"10.0.0.1\"}]}";
Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
classMap.put("report_list", FlowStatistics.class);
JSONObject jsonObject1 = JSONObject.fromObject(tmp);
FlowReport fr = (FlowReport) JSONObject.toBean(jsonObject1, FlowReport.class, classMap);
for (FlowStatistics obj : fr.getReport_list()) {
System.out.println(obj.getSip());
}