What is JSON parsing in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can parse JSON Response with Rest Assured. To parse a JSON body, we shall use the JSONPath class and utilize the methods of this class to obtain the value of a specific attribute.

We shall first send a GET request via Postman on a mock API URL and observe the Response body.

Example

Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
public class NewTest {
   @Test
   void responseParse() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //input details
      RequestSpecification h = RestAssured.given();

      //get response
      Response res = h.get("/a1b7b64c-0204-409a-aa0c-e8314a5ddabf");

      //Response body
      ResponseBody b = res.getBody();

      //convert response body to string
      String responseBody = b.asString();

      //JSON Representation from Response Body
      JsonPath jsnPath = res.jsonPath();

      //Get value of Location Key
      String s = jsnPath.get("student");
      System.out.println("Course name: " + s);
      String std = jsnPath.get("standard");
      System.out.println("Standard: " + std);
      String m = jsnPath.get("marks");
      System.out.println("Marks: " + m);
   }
}

Output

raja
Updated on 18-Nov-2021 11:09:14

Advertisements