1. 测试接口
@PostMapping("/test")
public RetResult test(@RequestBody JSONObject jsonObject) {
JSONObject content = (JSONObject)jsonObject.getJSONArray("content").get(0);
Account account = content.toJavaObject(Account.class);
System.out.println(account);
return RetModel.ok().setData(content);
}
//测试数据
{
"content": [
{
"accountNo": "111",
"accountName": "得到"
},
{
"accountName": "222",
"accountName": "方法"
}
]
}
JSONObject jsonObject = (JSONObject) jsonArray.get(0); 这行报错
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.alibaba.fastjson.JSONObject
问题分析
controller方法参数值是由springmvc框架,jackson解析为LinkedHashMap的。参数为JSONObject,是fastjson类型,本质上数组内部类型为LinkedHashMap,不能强转为JSONObject
2. 优化方法1
@PostMapping("/test")
public RetResult test(@RequestBody JSONObject jsonObject) {
JSONArray jsonArray = jsonObject.getJSONArray("content");
Object object = jsonArray.get(0);
JSONObject jsonObject2 = (JSONObject) JSON.toJSON(object); // 优化为 通过JSON.toJSON转为JSONObject
Account account = jsonObject2 .toJavaObject(Account.class);
return RetModel.ok().setData(content);
}
3. 优化方法2
@PostMapping("/test")
public RetResult test(@RequestBody Map<String, List<Account>> map){
//直接使用map就可以了,也可以使用 Map<String, Object> map, 获取值可以强转
return RetModel.ok().setData(map);
}