SpringMVC后台接收Ajax传递复杂对象报错property path is neither an array nor a List nor a Map
SpringMVC后台接收Ajax传递复杂对象报错property path is neither an array nor a List nor a Map
今天遇到一个问题,我在前台传递参数后台使用javabean接收的时候报错property path is neither an array nor a List,大体意思是说属性既不是数组也不是列表。
一、存在问题的代码
JS代码:
var param = {
pvqId:pvqId,
chooseOptionId:chooseOptionId,
optionList:[{
pvoId:pvoId,
fillOptionContext: fillOptionContext
}]
};
$.post("/wx/doExamAnswer", param, function (data) {
console.log(data);
}, "json");
Java代码:
@RequestMapping(value = "/wx/doExamAnswer", method = RequestMethod.POST)
@ResponseBody
public ResponseResult doExamAnswer(ExamAnswerForm examAnswerForm) {
//......
return ResponseResult.build(ResponseCodeEnum.SUCCESS, "");
}
/**
* @Description 用户答题提交DTO
* @Author jie.zhao
* @Date 2019/11/4 14:47
*/
public class ExamAnswerForm {
private Long pvqId;
private String chooseOptionId;
List<ExamAnswerOption> optionList;
//省略get/set
}
class ExamAnswerOption{
private Long pvoId;
private String fillOptionContext;
//省略get/set
}
以上传参和接收参数都是比较常规的写法,根据报错提示可能是List
二、问题原因
原因是因为JQuery会将你的这个optionList参数映射成这样:
optionList[0][pvoId]=1
optionList[0][fillOptionContext]=111
而SpringMVC需要这样的参数格式:
optionList[0].pvoId=1
optionList[0].fillOptionContext=111
三、解决方案
使用@RequestBody注解将请求中的json参数转换成java对象,使用时需要前台将content-Type设置为application/json,必须要将JSON对象转换为JSON字符串。
JS代码:
var param = {
pvqId:pvqId,
chooseOptionId:chooseOptionId,
optionList:[{
pvoId:pvoId,
fillOptionContext: fillOptionContext
}]
};
$.ajax({
url: "/wx/doExamAnswer",
type: "POST",
data: JSON.stringify(param),
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
},
error:function () {
}
});
Java代码:
@RequestMapping(value = "/wx/doExamAnswer", method = RequestMethod.POST)
@ResponseBody
public ResponseResult doExamAnswer(@RequestBody ExamAnswerForm examAnswerForm, HttpServletRequest request) {
//获取cookie
String openId = CookieUtil.getCookie(request, Constant.OPENID_COOKIE);
examService.doExamAnswer(examAnswerForm, openId);
return ResponseResult.build(ResponseCodeEnum.SUCCESS, "");
}
问题已解决
参考文档:
https://stackoverflow.com/questions/5900840/post-nested-object-to-spring-mvc-controller-using-json
-------------已经触及底线 感谢您的阅读-------------