前景:
net.sf.ezmorph.bean.MorphDynaBean cannot be cast to com.console.demo.web.model.XXX
//jsonObject:所有参数 //FreightTemplate对象里面包含一个 private List<FreightTemplateCity> freightTemplateCity; 类似于一父多子 FreightTemplate freightTemplate = (FreightTemplate) JSONObject.toBean(JSONObject.fromObject(jsonObject.get("freightTemplate")), FreightTemplate.class); //先新增freightTemplate businessDao.insertSelective(freightTemplate); //取出子list对象 List<FreightTemplateCity> freightTemplateCities = freightTemplate.getFreightTemplateCity(); //遍历新增子对象 //PS:这句for循环报的错 for (FreightTemplateCity freightTemplateCity : freightTemplateCities) { freightTemplateCity.setTemplateId(freightTemplate.getId()); businessDao.insertFreightTemplateCity(freightTemplateCity); }
发现我的子对象自动被转换成了net.sf.ezmorph.bean.MorphDynaBean对象,找了半天不知道哪里转成这个的,于是想到直接把
JSONObject object = (JSONObject) jsonObject.get("freightTemplate");//从所有对象里取到父对象,转成JSONObject类型 JSONArray array = (JSONArray) object.get("freightTemplateCity");//从JSONObject里面取到"freightTemplateCity"转成JSONArray格式
然后JSONArray就可以直接转list了,下面贴代码
FreightTemplate freightTemplate = (FreightTemplate) JSONObject.toBean(JSONObject.fromObject(jsonObject.get("freightTemplate")), FreightTemplate.class); //先新增freightTemplate businessDao.insertSelective(freightTemplate); //------------这一段转换对象类型---------------- JSONObject object = (JSONObject) jsonObject.get("freightTemplate"); JSONArray array = (JSONArray) object.get("freightTemplateCity"); List<FreightTemplateCity> list = JSONArray.toList(array, new FreightTemplateCity(), new JsonConfig()); //---------------------------- for (FreightTemplateCity freightTemplateCity : list) { freightTemplateCity.setTemplateId(freightTemplate.getId()); businessDao.insertFreightTemplateCity(freightTemplateCity); }
但是因为不知道具体发生转换的原因,不知道这样做有没有什么影响,如果有其他好的办法,望不吝啬指教一下