springMVC无法接收完整的json数据

时间:2016-11-07 09:23:56

标签: json spring spring-mvc controller

我尝试使用$ .ajax和@RequestBody,但是当我使用它来传递Integer类型时。它无法读取数据并打印null@RequestBody可以接收哪种数据?

这是我的代码:

var user = {
    "username" : "test",
    "password" : "test",
    "age" : 1
};
$.ajax({
    url: "/test1",
    type: "POST",
    data: JSON.stringify(user),
    contentType:"application/json; charset=utf-8",
    success: function() {
        alert("success")
    }
})

这是我的控制者:

@RequestMapping(value = "/test1")
public String test2(@RequestBody User user) {

    //Can't receive the Param.
    //   console result : null
    System.out.println(user.getAge());

    //Nothing wrong
    //console result: 
    //                  username:  test
    //                  password:  test
    System.out.println(user.getUsername()); 
    System.out.println(user.getPassword());
    return "test";
}

这是User class:

public class User {
    private Integer age;
    private String username;
    private String password;

    //Setting and Getting
}

1 个答案:

答案 0 :(得分:0)

我发现了问题所在。在用户类中:

public class User {
    //It should be `int`
    private Integer age;
}

int是基本数据类型。 Integer是一个包装类。我需要转换数据类型。