2014-01-16 42 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

相关问题