Search code examples
apiseleniumrest-assuredrest-assured-jsonpath

In Rest Assured while trying to get token facing issue "Failed to parse the JSON document"


public void appTocken() {
RestAssured.baseURI ="https://localhost";
RequestSpecification request = RestAssured.given();

String payload= "{   \"client_id\": \"ahsan@gmail.com\",\r\n"
        + "    \"client_secret\": \"1212\",\r\n"
        + "    \"isInternalUser\": true,\r\n"
        + "    \"grant_type\": \"client_credentials\"\r\n"
        + "}";
request.header("Content-Type", "application/json");
Response responseFromApp =  request.body(payload).post("/auth/oauth/oidc/login-token");
responseFromApp.prettyPrint();

String jsonString = responseFromApp.getBody().toString(); String tockenGenerated = JsonPath.from(jsonString).get("access_token");

}


Solution

  • String jsonString = responseFromApp.getBody().toString(); 
    

    converts the object into string string object it doesn't give the json string , use :

    String jsonString = responseFromApp.getBody().asString(); 
    

    if pretty print is empty then asString() also will be empty

    A working example:

    Response maxJson = RestAssured
                .given().header("Content-type", "application/json").body("{\r\n"
                        + "         \"name\": \"morpheus\",\r\n" + "            \"job\": \"leader\"\r\n" + "        }")
                .post("https://reqres.in/api/users");
        maxJson.prettyPrint();
    
        String jsonString = maxJson.getBody().asString();
        System.out.println(jsonString);