weixin_45072956
2022-01-13 14:29
采纳率: 50%
浏览 155

@requestbody:无法将json数据映射为实体类

Spring_mvc 客户端采用ajax请求向服务器端传递json数据,利用@requestbody实现集合映射。

后端采用@requestbody String可以正常接收,但@requestbody List<实体类>出现错误,前端抓包出现 http 415错误,

img

前端代码:
<script>
    //发送ajax请求
    var userList = new Array();
    userList.push({username:"zhangsan","age":18});
    userList.push({username:"lisi",age:28});

    $.ajax({
        type:"POST",
        url:"${pageContext.request.contextPath}/user/quick5",
        data:JSON.stringify(userList),
        contentType:"application/json;charset=utf-8"
    });
</script>
前端抓包情况:

img

后端代码:
  @RequestMapping(value="/quick5")
    @ResponseBody
    public void  save5(@RequestBody List<User> list) throws IOException {
        System.out.println(list.toString());
        return;
    }
User类:

public class User {

    @JsonProperty(value="username" )
    private String username;
    @JsonProperty(value="age" )
    private int age;

    public User(){}
    public User(String username,int age){
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }


}

已测试点:加了Jackson依赖包;spring-mvc加了 mvc:default-servlet-handler/;前端请求的数据是json类型

8条回答 默认 最新

相关推荐 更多相似问题