I have the following json and want to create a list from the display names, the json can have many different types not necessarily only 2:
{"data": [
{
"types": {
"1": {
"display_name": "123",
},
"2": {
"display_name": "321",
},
}
}
I’ve tried the following:
JsonPath json = response.jsonPath();
List<String> list = json.getList("data.types.*.display_name");
to get the display names, I can easily replace the "*" with "1" or "2" but I don’t know what the name of the types will be (not necessarily 1 or 2, could be any string).
I want to create a list of strings from all of the display names in the json.
2
Answers
Creating a list from a JSON response using JsonPath in RestAssured with Java, you can do using number of these steps :
Import the required libraries for RestAssured and JsonPath.
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
Send a GET request to your API endpoint and retrieve the JSON response as a string.
String response = RestAssured.get("your_api_endpoint").asString();
Create a JsonPath object by passing the response string to it.
JsonPath jsonPath = new JsonPath(response);
Use the JsonPath object to extract the desired list from the JSON structure. Specify the JSON path expression for the list you want to extract.
List myList = jsonPath.getList("path.to.list");
Replace "path.to.list" with the actual JSON path expression to your desired list. For example, if the JSON response has an array of names at the root level, you can use $ to represent the root and specify the property name:
List names = jsonPath.getList("$.names");
Store the extracted list in a type List variable.
You can then use the list for further processing or manipulation in your code.
Note: adjust the JSON path expression to match the structure of your JSON response and the specific list you want to extract.
I think JsonPath jayway is better in this case. The code would be