Search code examples
javarest-assuredjackson-databind

how to deserialize the response via rest assured and Java


I'm sending a post request for the Login API of Demoblaze Website https://www.demoblaze.com/. I've searched over the internet about their official API documentation, and have found the postman collection that is used for this.

The login API specs found in postman:

endpoint: https://api.demoblaze.com/login

payload:

{
   "username": "horacioss1",
    "password": "1234567890"
}

when I send the request I get the following response:

"Auth_token: aG9yYWNpb3NzMTE2OTc2NDM="

The question here is how can I create a POJO class for the following response:

"Auth_token: aG9yYWNpb3NzMTE2OTc2NDM="

as it's just a string not a key-value pair.


Solution

  • Since it's a String, you cannot use default deserialization in Rest-Assured. To get token, just split String and get it.

    String res = given()...asString();
    String token = res.split(" ")[1];
    System.out.println("token);
    //aG9yYWNpb3NzMTE2OTc2NDM=
    

    if you want to do something like POJO (it's little bit over skill), then here you are:

    @Test
    void q77275023() {
        String res = given()...asString();
        String token = new Auth(res).getAuthToken();
        System.out.println("token = " + token);
    }
    
    static class Auth {
        private String authToken;
    
        public Auth(String res) {
            String value = res.split(" ")[1];
            this.authToken = value;
        }
    
        public String getAuthToken() {
            return authToken;
        }
    }