2014-01-16 44 views
28

我得到的反應是這樣的:放心。是否有可能從請求json中提取值?

Response response = expect().statusCode(200).given().body(requestBody).contentType("application/json") 
.when().post("/admin"); 
String responseBody = response.getBody().asString(); 

我在responseBody一個JSON:

{"user_id":39} 

可以用休息,放心的方法只有這個值= 39我解壓到字符串?

+0

嘗試尋找關於如何在Java中解析JSON的信息 - 將JSON(在你的情況下)轉換成一個Map。不幸的是,你會發現大約20種不同的方法來完成它,其中大部分都太複雜了,但Java大師似乎喜歡這樣。 –

+0

謝謝,@HotLicks,我知道這個決定,我一直在尋找答案,只有放心。看起來它無法做到。 – Jay

回答

14

我找到了答案:)

使用JsonPathXmlPath(如果你有XML)從響應體中獲取數據。

在我的情況:

JsonPath jsonPath = new JsonPath(responseBody); 
int user_id = jsonPath.getInt("user_id"); 
+0

確實,在官方文檔中:https://code.google.com/p/rest-assured/wiki/Usage#JSON_(using_JsonPath_) – emgsilva

+2

這只是普通的vanilla JSON訪問。任何JSON套件都可以做。 –

35

你也可以這樣做,如果你只是在提取「USER_ID」興趣:

String userId = 
given(). 
     contentType("application/json"). 
     body(requestBody). 
when(). 
     post("/admin"). 
then(). 
     statusCode(200). 
extract(). 
     path("user_id"); 

在其最簡單的形式,它看起來是這樣的:

String userId = get("/person").path("person.userId"); 
9

有幾種方法。我個人使用以下物質:

提取單個值:使用JsonPath得到正確的

Response response = 
given(). 
when(). 
then(). 
extract(). 
     response(); 

String userId = response.path("user_id"); 

提取物之一:

String user_Id = 
given(). 
when(). 
then(). 
extract(). 
     path("user_id"); 

與當你需要一個以上的整個處置工作類型:

long userId = 
given(). 
when(). 
then(). 
extract(). 
     jsonPath().getLong("user_id"); 

最後一個是真正有用的,當你想匹配對e值和類型,即

assertThat(
    when(). 
    then(). 
    extract(). 
      jsonPath().getLong("user_id"), equalTo(USER_ID) 
); 

其餘的保證文件是相當描述和充分的。有很多方法可以實現你正在問的問題:https://github.com/jayway/rest-assured/wiki/Usage

相關問題