错误 javax.json.stream.JsonParsingException:进行 AJAX API 调用时

Error javax.json.stream.JsonParsingException: when making an AJAX API call

我开发了一个基于 Web 的程序,在我的后端使用 java 球衣,在我的前端使用 jsp。当我使用 Ajax 进行 post API 调用时,我的后端出现以下异常。

javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)

我想我通过 Ajax API 调用传递的数据有问题。

这是我的 ajax API 电话:

var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');


$.ajax({
    type: "POST",
    url: $url,
    contentType: "application/json",
    data: obj,
    dataType: 'json',
    success: function () {
        alert("successed");

    }
});

这是我的后端实现代码:

@Path("testing")
public class test {
    UserRepository userRepo=new UserRepository();
    @Path("users")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
    userRepo.createUser(a);
    return a;
 }
}

您应该将数据作为 JSON 字符串发送,而不是 JSON 对象。避免代码中的 JSON.parse

var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';

或者,我会构造 JS 对象,然后在其上应用 JSON.stringify。这样,代码可读性更强:

var data = {
    userName: "John",
    password: "hgvv",
    img: "New York",
    fname: "kjbjk",
    lname: "bkbkkj",
    tp: "buhb",
    address: "jhbjhb",
    type: "user"
};

$.ajax({
    type: "POST",
    url: $url,
    contentType: "application/json",
    data: JSON.stringify(data), // added JSON.stringify here
    dataType: 'json',
    success: function () {
        alert("successed");
    }
});