【问题标题】:Error javax.json.stream.JsonParsingException: when making an AJAX API call错误 javax.json.stream.JsonParsingException:进行 AJAX API 调用时
【发布时间】:2020-07-20 11:51:59
【问题描述】:

我开发了一个基于 Web 的程序,在后端使用 java jersey,在前端使用 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;
 }
}

【问题讨论】:

    标签: java jquery json ajax jersey


    【解决方案1】:

    您应该将数据作为 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");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 2014-02-21
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 2022-01-20
      • 2021-09-30
      相关资源
      最近更新 更多