项目中出行java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx(实体类)异常的原因:
参数如下:
{
"appId": 101,
"tokenId": 201,
"sign": 1,
"userId": 45,
"traineeInfo":"{\"name\":\"马继涛\",\"gender\":1,\"birth\":\"19930906\",\"idCardNo\":\"2012050614\",\"school\":\"北京第三中学\",\"contact\":\"18866666666\"}",
"relationship":"母子",
"orders": [{
"amount": 200,
"totalAmount":200,
"payMethod":2,
"isTeacherQualified":"true",
"courseCode": "51bf186450d8bc11ebb49b005056a7973c",
"orderId": 20210708006,
"merRecvInfo":"{\"merchantPayBal\":\"21343323\"}",
"teacherInfo":"{\"isTeacherCertain\":1, \"teacherName\":\"王XX\", \"isTeacherQualified\":1 }"
},
{
"amount": 300,
"totalAmount":300,
"payMethod":1,
"isTeacherQualified":"false",
"courseCode": "87f06c1211d94f11eb9c8f68545a856785",
"orderId": 20210708005,
"merRecvInfo":"{\"merchantPayBal\":\"1112222333\"}",
"teacherInfo":"{\"isTeacherCertain\":1, \"teacherName\":\"马XX\", \"isTeacherQualified\":0 }"
}
]
}
后端如果用BeanUtils.populate(contractInfo, body);
会导致orders内部结构是List
而不是List,遇到这种情况,不要着急,我们不是拿不到它的值,而是跟我们预期的不太理想,那我们就想办法让它达到预期的效果,就要用到fastjson来处理了。
List<OrderDo> orderDos = JSON.parseArray(JSON.toJSONString(contractInfo.getOrders()), OrderDo.class);
contractInfo.setOrders(orderDos);
com.alibaba
fastjson
1.2.44
//1. List
JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(list)); /**list为 List
//2.JSON 转成List
List<ChannelItem> channelItemList = JSON.parseArray(itemJson,ChannelItem.class); /** itemJson: JsonArray ChannelItem : 对象bean类**/
//3. Map 转 JSON
JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(itemMap)); /** itemMap 为 Map**/
//4.JSON 转 Map
Map<String, Object> itemMap = JSONObject.toJavaObject(itemJSONObj, Map.class); /** itemJSONObj JSONObject**/
//5. JSONObject 转 JavaBean
Student student = JSON.parseObject(JSONObjectStr, new TypeReference<Student>() {}); //因为JSONObject继承了JSON,所以这样也是可以的
//6.JSONObject 转 Map
Map<String ,String> param = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Map<String, String>>(){});
json转换来自于:https://blog.csdn.net/sinat_35626559/article/details/78919736