通过RestAssured API调用后,我从REST API获得响应到Response对象。
响应正文是json,我想从中得到特定的键值?
以下是代码
Response res = given()
.relaxedHTTPSValidation()
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.get(url);
String rbody = res.body().asString();
如何在rbody
字符串中获取特定键值?
答案 0 :(得分:2)
Response
类使用方法path()
,用户可以给json路径获取特定值。
例如: -
Response res = given()
.relaxedHTTPSValidation()
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.get(url);
String value = res.path("root.childKey").toString();
root.childKey
是json元素的路径
答案 1 :(得分:2)
属于Restassured的JasonPath类是我用于项目的类。首先,您需要使用以下命令导入JsonPath类:
import com.jayway.restassured.path.json.JsonPath;
然后,您需要传递JSON字符串并使用它来创建JsonPath对象。从JsonPath对象中,您可以使用该键来获取相应的值。以下代码适合您。
Response res = given()
.relaxedHTTPSValidation()
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.get(url);
String rbody = res.asString();
JsonPath jp = new JsonPath( rbody );
String value = jp.getString( "your.key" );
答案 2 :(得分:1)
JSON的格式如下{someProprty:" someValue"}因此,您不想将其作为字符串获取,而是希望访问该特定属性。即:b.body.someProperty
注意:我强烈建议您将回复命名为res
或response
。您不会喜欢b
作为回复。
How to access JSON Object name/value?
JSON也可以格式化为{somePropertyThatIsNumerical:1}或者可以包含数组。
答案 3 :(得分:0)
baseURI="url";
Map<String,String> reqParam=new HashMap<String,String>();
reqParam.put("loginID","abc");
reqParam.put("password","123");
JSONObject reqObjects=new JSONObject(reqParam);
Response response =
given()
.header("Content-Type", "application/json").accept(ContentType.JSON)
.when()
.body(reqObjects.toJSONString()).post("/v1/getDetails")
.then().log().body().extract().response();
String responseBody= response.asString();
JsonPath path=new JsonPath(responseBody);
String key=path.getString("path.key");