简体   繁体   中英

How extract response to String and save it to variable

Being new to Java/JSON/REST Assured topics, I would like to extract a parameter of "token": from a JSON response body as a String and store it as variable which I could take to some other classes and use there. However, I have tried it and have not found a way. Below is part of a code which I have created at the beginning in a same manner as other requests stored in this class, but this is the first one from which I need something from the response:

public FakeTokenVO fakeToken() {         
  String payload = "payloadthere";         
  return given(specBuilder.fakeTokenRequestSpecification())                 .
       body(payload)                 
      .log().all()                 
      .when()                 
      .post(RestApiRoutes.FAKE_URI)                 
      .then()                 
      .log().all()                
      .extract()                 
      .response()                 
      .as(FakeTokenVO.class); 
}

Don't mind about the payload and those VO classes as it is stored as data model somewhere else. Response from the request made looks like this:

{
    "createTokenResponse": {
        "createTokenSuccess": {
            "token": "token_with_somewhere_about_700_characters"
        }
    }
}

Here is how I have tried to modify it to get the part of response which I need later (the token to authorize other requests):

@Test     
public void fakeToken() 
{ 
    String payload = "payloadthere";         
    String token = given(specBuilder.fakeTokenRequestSpecification())             
    .body(payload)             
    .log().all()             
    .when()             
    .post(RestApiRoutes.FAKE_URI)             
    .then()             
    .log().all()             
    .extract()             
    .response()             
    .body().path("createTokenResponse.createTokenSuccess.token");          
    System.out.print(token);     
}

This test returns me a value which I needed, but I do not know how to implement it as a method instead of test. Please help how should I approach it? What am I missing there? I tried to search for answers, but I haven't found a solution yet or do not know how to implement it in my part of the code.

I assume that you can get your response as a String. So all you need to do is to parse your Json String. For that you can use any available Json parser. The most popular ones are Json-Jackson (also known as Faster XML) or Gson (by Google). Both are very well known and popular. (My personal preference is Jackson, but it is a matter of opinion).

However, For simplistic cases like this I wrote my own utility (a thin wrapper over Jackson library) that allows you to parse Json String very simply without learning relatively complex libraries. With my utility your code may look like this:

try {
    Map<String, Object> map = JsonUtils.readObjectFromJsonString(jsonStr, Map.class);
    Map<String, Object> innerMap = map.get("createTokenResponse");
    Map<String, Object> innerMap2 = map.get("createTokenSuccess");
    String token = innerMap.get("token");
} catch (IOException e) {
    e.printStacktrace();
}

Or you can create your own classes such as

public class TokenResult {
    String token;
    //getter and setter
}

public class TokenHolder {
    private TokenResult createTokenSuccess;
    //setter and getter
}

public class TokenResponse {
    private TokenHolder createTokenResponse;
    //setter and getter
}

And than your code may look like this:

try {
    TokenResponse response = JsonUtils.readObjectFromJsonString(jsonStr, TokenResponse .class);
    String token = response.getCreateTokenResponse().getCreateTokenSuccess().getToken();
} catch (IOException e) {
    e.printStacktrace();
}

Here is a Javadoc for JsonUtils class. This Utility comes as part of Open Source MgntUtils library written and maintained by me. You can get the library as maven artifact on Maven Central here or on the github (including source code and javadoc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM