“parsererror”SyntaxError:意外的令牌c

时间:2016-03-01 09:59:18

标签: java rest

我想在我的Java Rest服务中发布json数据, 将数据从jQyery Ajax发布到Rest Service时返回:

“parsererror”SyntaxError:意外的令牌c

Java对象类

public class SimpleObject {
private int id;
private String name;

public SimpleObject(){

}

public SimpleObject(int id, String name) {
    this.id = id;
    this.name = name;
}

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

休息服务

      @POST
      @Path("/postjson")
      @Consumes(MediaType.APPLICATION_JSON)
      public Response jsonFunc(SimpleObject simpleobjcet){
          String output = simpleobjcet.toString();
          return Response.status(201).entity(output).build();
      }

jQuery Ajax客户端代码

$.ajax({
        url: 'http://localhost:8080/RestExample/resources/MyRestService/postjson',
        type: 'POST',
        data: '{"id":0,"name":"salih"}',
        contentType: 'application/json',
        dataType: 'json',
        success: function(responseData, textStatus, jqXHR)
        {    
            console.log(responseData);
        },
        error: function (responseData, textStatus, errorThrown)
        {
            console.log(responseData, textStatus, errorThrown);
            alert('Error' + textStatus);
        }
    });

2 个答案:

答案 0 :(得分:1)

SimpleObject.toString()不会返回JSON。由于您设置了dataType: 'json',因此jQuery也希望响应为JSON。

更改SimpleObject.toString()以生成JSON,或将dataType更改为text

答案 1 :(得分:0)

感谢@Tichodroma,我找到了解决方案,我更改了RestService代码并且工作正常! 新的RestService代码..

 @POST
      @Path("/postjson")
      @Consumes(MediaType.APPLICATION_JSON)
      public SimpleObject json(SimpleObject simpleObject){
            ObjectMapper mapper = new ObjectMapper();
            String jsonInString="";
            try {
                jsonInString = mapper.writeValueAsString(simpleObject);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            System.out.println(jsonInString);       
          return simpleObject;
      }