SpringMVC ajax请求参数为json时注意事项

SpringMVC Ajax请求参数为json时的几个注意事项

  1. 如果请求参数为json,请求时必须加上contentType:‘application/json;charset=UTF-8’

  2. ① 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";
    }
    
  3. 如果要传一个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";
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值