澤西

2016-07-02 115 views
0
@GET @Path("/ids/{printerid}") 
@Produces({"application/json", "application/xml"}) 
public Printer getPrinter(@PathParam("printerid") String printerId) { ... } 

返回XML/JSON是一段代碼示例這裏找到:https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e2089澤西

我的理解是:

  • 方法getPrinterHTTP method GET的呼籲被稱爲路徑/ids/{printerid}
  • 該方法Produces或者jsonxml結果
  • 該方法返回類型打印機的Object,由URI

我不明白的是,返回的打印機是如何表示爲xml/json文件所提供的ID來標識。我們以這種方式返回打印機,那麼我們如何從中獲得xml/json文件?

回答

2

這是Jersy圖層/彈簧控制器的整體思想,它們封裝它並將類轉換爲JSON。你可以有相同的結果與GSON

Gson gson = new Gson(); 
String json = gson.toJson(printerObject); 
System.out.println(json); 

不知道Jersy使用GSON,但邏輯很可能是同一

+0

確定。據我瞭解,我不必爲轉換本身做任何事情。 現在假設我調用一個生成XML的方法,在我的情況下,如何在客戶端(瀏覽器)中顯示它。當我打電話給該方法時,什麼都不顯示 – user6454491

+1

檢查網絡瀏覽器網絡控制檯,檢查響應主體或使用fiddler查看從服務器獲得的數據,並確保正確解析它 – USer22999299

+1

謝謝。看起來有一個內部服務器錯誤。至少我隱約知道我現在應該看什麼 – user6454491

2

當您要求從CLIEN端的服務,你總是提到的內容類型有它表示在xml或json中接受的響應。

$http({ 
     method: "GET", 
     contentType: "application/json", 
     url: baseUrl + '/xyz' + id 
     }).success(function (response) { 
     console.log(response); 
     // you can also use 
     console.log(JSON.stringify(response); 
     }).error(function (response) { 
     console.log(response); 
     });