How to convert a APi response String to Json in RestAssured
- Dev Raj Sinha
- Jun 18, 2023
- 1 min read
To convert an API response string to JSON in RestAssured, you can use the `JsonPath` class provided by RestAssured. The `JsonPath` class allows you to parse the response string and provides various methods to extract data from the JSON structure. Here's an example of how you can convert an API response string to JSON using RestAssured:
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
String responseString = "{
\"name\": \"John Doe\",
\"age\": 30,
\"email\": \"johndoe@example.com\"
}";
JsonPath jsonPath = new JsonPath(responseString);
In this example, we have a response string representing a JSON structure. We create a `JsonPath` object by passing the response string to the `JsonPath` constructor.
Once you have the `JsonPath` object, you can use its methods to extract data from the JSON structure. Here are a few examples:
String name = jsonPath.getString("name");
int age = jsonPath.getInt("age");
String email = jsonPath.getString("email");
In this example, we use the `getString()` and `getInt()` methods of the `JsonPath` class to extract the values of the "name", "age", and "email" fields from the JSON structure.
You can also perform more complex operations with `JsonPath`, such as extracting nested values, retrieving arrays, and filtering data based on conditions. Refer to the RestAssured documentation for more details on using `JsonPath` and its available methods.
By using the `JsonPath` class provided by RestAssured, you can easily convert an API response string to JSON and extract data from it in a structured manner.
Comments