java - 放心 : How do I return JSON response as a String? (Java)

标签 java rest-assured rest-assured-jsonpath

我如何使用我的代码将 JSON 响应作为字符串返回?

目的:我想调用getAccessToken()在它从 json 响应正文中获取 accessToken 并需要将其作为 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.

最佳答案

只需编写一个简单的可重用方法来使用 JSONPath 提取值并在您的代码中调用该方法,这是一个示例

可重复使用的方法:

public static String getJsonPath(Response response, String key) {
    String complete = response.asString();
    JsonPath js = new JsonPath(complete);
    return js.get(key).toString();
}

测试:

public static void main(String[] args) {

    Response res = 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().response();
    String value = getJsonPath(res, "accessToken");
    
    System.out.println(value);
}

更新:

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();
}

@Test
public void testAuthValidator() throws InterruptedException, IOException, GeneralSecurityException {
    String sentCode = GmailUtility.getVerificationCode();
    System.out.println(sentCode);
    String Token = getToken("accessToken");
    System.out.println(Token);
    driver = initializeDriver();
    driver.get(env.API_Website);
    AuthApi auth = new AuthApi(driver);
    auth.getAuthorizeButton().click();
    auth.getValueField().sendKeys("Token " + Token);
}

你可以用这个得到任何值

关于java - 放心 : How do I return JSON response as a String? (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747172/

相关文章:

java - 递归谢尔宾斯基三角形

Java-设置 datetime17 :30 if the current time is before 17:00

java - 扫描仪在大约 2400 个字符后切断我的字符串

java - 为所有请求添加 header

java - 如何在 Rest Assured 中为失败的 REST 调用实现重试逻辑

apache - org.apache.http.ConnectionClosedException : Premature end of chunk coded message body: closing chunk expected

java - 如何使用response.path计算响应(Json)的总和?

java.net.ConnectException : Connection refused: connect, 启动已取消

java - 有没有办法根据另一个元素值查找 JSON 响应元素值?

java - 如何在放心的java中从值中找到键?