SpringMVC Ajax请求参数为json时的几个注意事项
-
如果请求参数为json,请求时必须加上contentType:‘application/json;charset=UTF-8’
-
① data写成标准json字符串格式’{“name”:“tom”,“age”:39}’,key必须加引号,单引号/双引号均可,但必须得加,大括号外边也必须加上引号否则会报错,控制台会报错,报错如下
警告 [http-nio-8082-exec-12] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotReadable Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'name': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name': was expecting ('true', 'false' or 'null') at [Source: (PushbackInputStream); line: 1, column: 10]
② data写为JSON.stringify({“name”:“tom”,“age”:39}),此时json中的key可以不加引号。
以上两种情况,controller中应写为如下格式@RequestMapping("/xxx") public String testAjax(@RequestBody User user) { System.out.println(user); return "xxx"; }
-
如果要传一个json数组,则前端应写为
① data:’[{“name”:“tom”,“age”:39},{“name”:“tom1”,“age”:19}]’
② data: JSON.stringify([{“name”:“tom”,“age”:39},{“name”:“tom1”,“age”:19}])
controller中应写为@RequestMapping("/xxx") public String testAjax(@RequestBody List<User> userList) { System.out.println(userList); return "xxx"; }