2016-03-01 28 views
0

我要發佈JSON數據我的Java REST服務, 時後從jQyery阿賈克斯REST服務返回的數據:「parsererror」語法錯誤:意外的令牌Ç

「parsererror」語法錯誤:意外的令牌Ç

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; 
} 
} 

REST服務

 @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); 
     } 
    }); 
+0

誰給這個錯誤? Java編譯器? jQuery的? – 2016-03-01 10:07:41

+0

看看網絡通信。打開瀏覽器的開發人員工具,查看服務器回覆您的回覆的內容。我懷疑'String output = simpleobjcet.toString()'。 –

+0

給jQuery,當我用f12開發工具監視瀏覽器網絡時,Http response 200 ok,但jQuery給出這個錯誤 –

回答

0

Thanks @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; 
     } 
1

SimpleObject.toString()不返回JSON。既然你設置了dataType: 'json',jQuery也希望響應也是JSON。

要麼更改SimpleObject.toString()以生成JSON,要麼將dataType更改爲text