JSONObject.toBean 报java.lang.ClassCastException: java.lang.Class cannot be cast to **

来源:互联网 发布:中原农险数据脱敏 编辑:程序博客网 时间:2024/06/18 17:59

错误出现条件

代码:

JSONObject entityObj = importArray.getJSONObject(i);JsonConfig jsonConfig = new JsonConfig();jsonConfig.setRootClass(Entity.class);Entity entity= (Entity) JSONObject.toBean(entityObj, Entity.class, jsonConfig);

错误:

java.lang.ClassCastException: java.lang.Class cannot be cast to Entity

解决方法

代码:

JSONObject entityObj = importArray.getJSONObject(i);JsonConfig jsonConfig = new JsonConfig();jsonConfig.setRootClass(Entity.class);Entity entity= (Entity ) JSONObject.toBean(entityObj,  jsonConfig);

错误分析

toBean方法
在没有使用jsonConfig之前,其实使用的是:

toBean( JSONObject jsonObject, Class beanClass )

后来加入直接在末尾加入JsonConfig,实际上使用的是:

toBean( JSONObject jsonObject, Object root, JsonConfig jsonConfig )

转换时取rootClass的代码:

Class rootClass = root.getClass();

rootClass取值

0 0
原创粉丝点击