Ajax POST Spring json错误的字符

时间:2018-04-10 17:28:55

标签: json ajax spring spring-boot

这是我的用户保存控制器。

@ResponseBody
@RequestMapping(method= RequestMethod.POST,consumes= {"application/json"})
@JsonDeserialize(as = Users.class)
public ResponseEntity addUser(@RequestBody String jsonUser){
    try{
       ///

    }catch (Exception e){
        ///
    }
        return ResponseEntity.ok(HttpStatus.OK);
}

这是我的ajax帖子

 var obj = '{'
            +'"name" : '+name+','
            +'"surname" : '+surname+','
            +'"username" : '+username+','
            +'"email" : '+email+','
            +'"password" : '+password+','
            +'}';

        $.ajax({
            url: "/users",
            method: "POST",
            data: JSON.stringify(obj) ,
            dataType: 'json',
            success: function (response) {
                console.log(response);

            },
        });

如果我用邮递员发帖,发布的数据还可以。但是如果我用ajax发帖,控制器就会收到这个字符串

%22%7B%5C%22name%5C%22+%3A+asd%2C%5C%22surname%5C%22+%3A+asd%2C%5C%22username%5C%22+%3A+asd%2C%5C%22email%5C%22+%3A+asd%2C%5C%22password%5C%22+%3A+asd%2C%7D%22=

1 个答案:

答案 0 :(得分:0)

Json.stringify内传递javascript对象而不是字符串。像这样:

var obj = {
    name: name,
    surname: surname,
    username: username,
    email:  email,
    password: password
};

而不是

var obj = '{'
        +'"name" : '+name+','
        +'"surname" : '+surname+','
        +'"username" : '+username+','
        +'"email" : '+email+','
        +'"password" : '+password+','
        +'}';

由于您已经在Json.stringify中传递了一个字符串,因此它会进一步转义双引号和其他字符。