【问题标题】:springMVC can't receive full json dataspringMVC 无法接收完整的 json 数据
【发布时间】:2017-03-20 14:08:45
【问题描述】:

我正在尝试使用 $.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";
}

这是用户类:

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

    //Setting and Getting
}

【问题讨论】:

  • 你的 User 类是什么样子的?
  • 你的变量名应该和你的模型的字段名一样,在你的json对象中似乎你没有通过age所以它总是得到null结果
  • 在您的代码中,您正在设置 ID 参数,同时打印 user.getAge()
  • 我已经修改了我的代码并添加了我的 User 类。

标签: json spring spring-mvc controller


【解决方案1】:

我找到了问题所在。在用户类中:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2019-05-08
    • 2012-04-22
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多