如何将JSON响应作为字符串返回给我的代码?
目的:我想在从json响应体中获取accessToken后调用getAccessToken()
,并需要将其作为String
返回以供其他方法使用。
我正在尝试获取的响应示例:
"accessToken" : "The ID I need from here"
代码:
private String apiAccessToken;
public JsonPath getAccessToken() {
JsonPath jsonPath = given().header("X-API-KEY", Config.API_KEY).header("session", this.sessionID)
.header("username", this.userNameId).queryParam("code", verifiedCode).log().all()
.get(baseUri + basePath + "/vm1/verifyCode").then().log().all().extract().jsonPath();
this.apiAccessToken = jsonPath.get("accessToken");
return new JsonPath(apiAccessToken);
}
[添加 - 展示我如何使用下面评论中的解决方案]
我调用该方法的示例:
public static String getToken(String key) {
String res = given()
.header("X-API-KEY", Config.API_KEY)
.header("session", this.SessionId)
.header("username", this.UserName)
.queryParam("code", verifiedCode)
.log().all()
.get(baseUri + basePath + "/vm1 /verifyCode")
.then()
.log().all()
.extract().asString();
JsonPath js = new JsonPath(res);
return js.get(key).toString();
}
public static String getJsonPath(Response response, String key) {
String complete = response.asString();
JsonPath js = new JsonPath(complete);
return js.get(key).toString();
}
@Test
public void testAuthValidator() throws InterruptedException, IOException, GeneralSecurityException {
String sentCode = GmailUtility.getVerificationCode(); // Uses GMAIL API service to to read and get code from email and sends to getAccessToken
System.out.println(sentCode);
String Token = getToken("accessToken"); // Validates verification code. Spits out response for accessToken
System.out.println(validator);
driver = initializeDriver(); // Invokes Chrome
driver.get(env.API_Website); // Goes to api website
AuthApi auth = new AuthApi(driver);
auth.getAuthorizeButton().click(); // Clicks a text field on webpage
auth.getValueField().sendKeys("Token " + Token); // Need to call extracted response for the accessToken from getAccessToken.