HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of 解决办法

前端用ajax通过json传给后端,传递的数据是一个列表  localStorage.getItem('answers')。

[{"id":36,"ans":["pig","dog"]},{"id":37,"ans":["tiger","pig"]},{"id":38,"ans":["tiger","pig"]}]

ajax代码:

var json = localStorage.getItem('answers')
$.ajax({
	type:"POST",
	url:"/finishedWork",
	async:true,
	contentType: 'application/json;charset=UTF-8',
	data:JSON.stringify(json),
	success:function(response){
		if(response.code==200){
			alert("提交成功!");
			window.location.href = "/";
		}
	},
	dataType:"json"
});	

后端:

HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of 解决办法_第1张图片

    @ResponseBody
    @RequestMapping(value="/finishedWork", method = RequestMethod.POST)
    public Object finishedWork(@RequestBody List ans, HttpSession session){
    ....
}

按照常规操作,只要json的Key和RequestBody的属性名称一致,就能自动转换,但是却报错了。

通过一系列挣扎,几个小时的测试,最后发现是犯了一个很小的错误。

data:JSON.stringify(json),括号里面的type是String,但是正确的应该是一个Object

改成 data:JSON.stringify(JSON.parse(localStorage.getItem('answers'))), 就对了
 

你可能感兴趣的:(HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of 解决办法)