Read Many Values With JsonPath and XmlPath in REST Assured
Use JsonPath and XmlPath as objects, covering typed getters such as getInt and getList, maps and mapped objects, JSON that didn't come from an HTTP call, and XmlPath on an ISO 20022 payment status report.
Your test needs ten values from one page of customers, and extract().path(..) gives you one at a time. Another test has to check the consent webhook your service sends, a piece of JSON that never passes through a REST Assured request, and someone suggests adding a JSON library for it. In this guide, you’ll use JsonPath and XmlPath, the path engines behind body(..), as objects: query one response as often as you like, and read JSON and XML from anywhere.
Level: Intermediate · Time: 20 minutes · Part of: Module 4: Extracting Values and Mapping Objects, section 2
What You’ll Build
You’ll build a test class called JsonPathAndXmlPathTest with four tests. Two query a page of customers through a JsonPath; two read a webhook payload and a payment status report that never went over HTTP.
The first two tests send this request and check this response:
1
2
3
4
5
6
7
GET /api/v1/customers?size=3 HTTP/1.1
Host: localhost:<port>
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{"items":[{"id":"cust-1", ...},{"id":"cust-2", ...},{"id":"cust-3", ...}],"page":0,"size":3,"totalItems":5,"totalPages":2}
When you’re done, Maven reports four passing tests:
1
2
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Read a response with typed getters.
- Read maps and objects.
- Read JSON that didn’t come from HTTP.
- Read XML with XmlPath.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can extract values after validating a response, as taught in Extract Values From a Response in REST Assured, and read XML paths, from Check XML and HTML Responses in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
JsonPathAndXmlPathTestin a newsection_02package next to the class from the previous section, and follow every heading below. - Skip ahead: open the finished class (
JsonPathAndXmlPathTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Extract Values From a Response in REST Assured.
Out of scope: this guide doesn’t cover mapping a whole response body to a record, or generic types such as Page<Customer>; they’re taught in section 3.
Understand JsonPath and XmlPath
The problem. extract().path(..) reads one value, typed exactly as REST Assured read it. For many values from one response, a chain per value is long-winded, or sends the request again. And JSON or XML that doesn’t come from a REST Assured request, such as a webhook payload, a queue message or a file in src/test/resources, can’t be checked with body(..) at all.
The concept. io.restassured.path.json.JsonPath and io.restassured.path.xml.XmlPath are the classes that evaluate GPath. You get one from a response with extract().jsonPath() or extract().xmlPath(), or from any text with JsonPath.from(..) or XmlPath.from(..); a string, a File or an InputStream works. Each has typed getters:
| Getter | Returns |
|---|---|
getString(path) | The value as a String |
getInt(path), getLong(path), getDouble(path) | The value converted to that number type |
getBoolean(path) | The value as a boolean |
getList(path, type) | A list, with each element converted or mapped to type |
getMap(path) | An object as a Map |
getObject(path, type) | An object mapped to a Java type with the object mapper |
Unlike path(..), the getters convert: getLong("totalItems") works though REST Assured read the number as an Integer, and getString("totalItems") returns "5".
When to use each. Use body(..) when you check a response in the chain; it reports every failure with its path. Use extract().jsonPath() when you need many values from one response, or values for later requests. Use JsonPath.from(..) when the JSON didn’t come from a REST Assured request.
Extract the JsonPath once, and query it as often as you need.
Meet the API Under Test
The first two tests read the Customers and Consents API’s first page of customers, three per page. It holds two RETAIL customers and one BUSINESS customer, and five customers exist in total:
1
2
3
4
5
6
7
8
9
10
11
{
"items": [
{ "id": "cust-1", "name": "Anna de Vries", "email": "anna@example.nl", "segment": "RETAIL", "createdAt": "..." },
{ "id": "cust-2", "name": "Jan Jansen", "email": "jan@example.nl", "segment": "RETAIL", "createdAt": "..." },
{ "id": "cust-3", "name": "Bakkerij Bart B.V.", "email": "finance@bakkerijbart.nl", "segment": "BUSINESS", "createdAt": "..." }
],
"page": 0,
"size": 3,
"totalItems": 5,
"totalPages": 2
}
The last two tests send no request. They read text that a real system might receive:
- A consent webhook,
{"event": "consent.revoked", "data": {"consentId": "consent-7", "reason": "CUSTOMER_REQUEST"}}. - A simplified ISO 20022
pain.002, the payment status report a bank sends back after a payment file. Its group statusGrpStsisACCP, the code for “accepted”.
Your tests read these values:
totalItemsandtotalPages, as numbers.items[0].name,items.emailand whole customers, as strings, lists, maps and records.eventanddata.reasonfrom the webhook, andOrgnlMsgIdandGrpStsfrom the status report.
Read a Response With Typed Getters
Set Up the Test Class
Goal: create the test class with a helper that validates the page and returns its JsonPath.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.javanibble.module_04.section_02;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import com.javanibble.consents.ConsentsApi;
import com.javanibble.module_04.support.Models.Customer;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class JsonPathAndXmlPathTest {
private static ConsentsApi api;
@BeforeAll
static void startApi() {
api = ConsentsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static JsonPath firstPageOfCustomers() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(ConsentsApi.BASE_PATH)
.queryParam("size", 3)
.when()
.get("/customers")
.then()
.statusCode(200)
.extract().jsonPath();
}
}
What’s happening:
firstPageOfCustomers()validates the status before it extracts, as the previous section recommends, then returns theJsonPathfor the test to query.assertThatcomes from AssertJ, which reads well on plain Java values.Customeris a record from the module’sModelsclass.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Read Numbers, Strings and Lists
Goal: read four values from one JsonPath, each as the type you ask for.
1
2
3
4
5
6
7
8
9
@Test
void typedGetters() {
JsonPath page = firstPageOfCustomers();
assertThat(page.getInt("totalItems")).isEqualTo(5);
assertThat(page.getInt("totalPages")).isEqualTo(2);
assertThat(page.getString("items[0].name")).isEqualTo("Anna de Vries");
assertThat(page.getList("items.email", String.class)).hasSize(3).allMatch(email -> email.contains("@"));
}
What’s happening:
- The request is sent once, and the test queries the same
JsonPathfour times. getInt(..)andgetString(..)return the value converted to that type.getList("items.email", String.class)returns aList<String>, so AssertJ’s list assertions, such ashasSize(..)andallMatch(..), apply to it directly.
Checkpoint: run JsonPathAndXmlPathTest from your IDE. One test runs and passes.
A typed getter can’t return
nullfor a primitive.getInt("missing")throwsNullPointerException: Cannot invoke "java.lang.Integer.intValue()" ..., because there’s nointfor a missing value. Check that the field exists first, or usegetString(..), which returnsnull.
Read Maps and Objects
Read an Object as a Map and as a Record
Goal: read customers as a map, as one record and as a list of records.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void mapsAndObjects() {
JsonPath page = firstPageOfCustomers();
Map<String, Object> first = page.getMap("items[0]");
assertThat(first).containsEntry("segment", "RETAIL");
Customer third = page.getObject("items[2]", Customer.class);
assertThat(third.name()).isEqualTo("Bakkerij Bart B.V.");
assertThat(third.createdAt()).isNotNull();
List<Customer> all = page.getList("items", Customer.class);
assertThat(all).extracting(Customer::segment).containsExactly("RETAIL", "RETAIL", "BUSINESS");
}
What’s happening:
getMap("items[0]")returns an object as a map, with the field names as keys.getObject("items[2]", Customer.class)maps part of the body to a record. It uses the object mapper, Jackson 3 here, so the ISO 8601createdAtstring becomes anInstant.getList("items", Customer.class)maps every element, and AssertJ’sextracting(..)reads one field from each.
Checkpoint: run the class again. Two tests pass.
Pass the type to
getList(..). Without it,getList("items")returns maps, notCustomerrecords, so record methods such asCustomer::segmentaren’t available.
Read JSON That Didn’t Come From HTTP
Read a Webhook Payload
Goal: check JSON text with the same paths as a response.
1
2
3
4
5
6
7
8
9
10
11
@Test
void jsonThatDidntComeFromHttp() {
String webhook = """
{"event": "consent.revoked", "data": {"consentId": "consent-7", "reason": "CUSTOMER_REQUEST"}}
""";
JsonPath json = JsonPath.from(webhook);
assertThat(json.getString("event")).isEqualTo("consent.revoked");
assertThat(json.getString("data.reason")).isEqualTo("CUSTOMER_REQUEST");
}
What’s happening:
JsonPath.from(..)reads any JSON text. No request is sent.- The same GPath works, so
data.reasonreads a nested field as it would inbody(..). - This suits a webhook your service sends, a message it puts on a queue, or an expected response kept in a file.
Checkpoint: run the class again. Three tests pass.
JsonPath.from(..)parses lazily.JsonPath.from("{not json")succeeds, and the error,JsonPathException: Failed to parse the JSON document, appears only when you first read a value.
Read XML With XmlPath
Read a Payment Status Report
Goal: read an ISO 20022 status report with XmlPath and a root path.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void xmlPathWorksTheSameWay() {
String xml = """
<Document><CstmrPmtStsRpt><OrgnlGrpInfAndSts>
<OrgnlMsgId>MSG-42</OrgnlMsgId><GrpSts>ACCP</GrpSts>
</OrgnlGrpInfAndSts></CstmrPmtStsRpt></Document>
""";
XmlPath status = XmlPath.from(xml).setRootPath("Document.CstmrPmtStsRpt.OrgnlGrpInfAndSts");
assertThat(status.getString("OrgnlMsgId")).isEqualTo("MSG-42");
assertThat(status.getString("GrpSts")).isEqualTo("ACCP");
}
What’s happening:
XmlPath.from(..)reads XML text the same wayJsonPath.from(..)reads JSON.setRootPath(..)works likerootPath(..)in Shorten JSON Paths With Root Paths in REST Assured.- The XML rules from Module 3 apply: paths start with the root element, and values are text.
Checkpoint: run the class again. All four tests pass.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-04 -Dtest=JsonPathAndXmlPathTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_04.section_02.JsonPathAndXmlPathTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.496 s -- in com.javanibble.module_04.section_02.JsonPathAndXmlPathTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
The last two tests send no HTTP request at all.
Make a Test Fail
In typedGetters, change isEqualTo(2) on totalPages to isEqualTo(3) and run the command again. You should see a result similar to the following:
1
2
3
4
[ERROR] Failures:
[ERROR] JsonPathAndXmlPathTest.typedGetters:55
expected: 3
but was: 2
This message comes from AssertJ, not REST Assured, so it shows the two values but not the path that was read. The line number, 55, points you to the assertion. That’s the trade-off from the concept section: when you only need to check a value, body("totalPages", equalTo(3)) names the path in its failure.
Change isEqualTo(3) back to isEqualTo(2) and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
NullPointerException: Cannot invoke "java.lang.Integer.intValue()" ... | A typed getter read a missing value | Check the path, or use getString(..) |
JsonPathException: Failed to parse the JSON document | The text isn’t valid JSON | Check the source text; the error appears on the first read |
| A list element isn’t a record | getList(path) was called without a type | Pass the type, as in getList("items", Customer.class) |
Try It Yourself
Exercise 1: Read an Authorised Consent Webhook
Add a test called anAuthorisedConsentWebhook that reads this payload with JsonPath.from(..):
1
2
{"event": "consent.authorised", "createdAt": "2026-11-21T10:15:00Z",
"data": {"consentId": "consent-9", "permissions": ["ReadAccountsBasic", "ReadBalances"], "expiresInDays": 90}}
Check the consent id, that the permissions are exactly ReadAccountsBasic and ReadBalances in that order, and that it expires in 90 days.
Hint
Start from jsonThatDidntComeFromHttp. Use getList(path, String.class) for the permissions and getInt(..) for the number.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void anAuthorisedConsentWebhook() {
String webhook = """
{"event": "consent.authorised", "createdAt": "2026-11-21T10:15:00Z",
"data": {"consentId": "consent-9", "permissions": ["ReadAccountsBasic", "ReadBalances"], "expiresInDays": 90}}
""";
JsonPath json = JsonPath.from(webhook);
assertThat(json.getString("data.consentId")).isEqualTo("consent-9");
assertThat(json.getList("data.permissions", String.class)).containsExactly("ReadAccountsBasic", "ReadBalances");
assertThat(json.getInt("data.expiresInDays")).isEqualTo(90);
}
Exercise 2: Filter a Page and a Partly Rejected Report
Add a test called businessCustomersAndARejectedPayment. First, from firstPageOfCustomers(), read the names of the BUSINESS customers with one closure, and check that the only one is "Bakkerij Bart B.V.". Then read this status report, where the group status PART means “partly accepted”:
1
2
3
4
5
6
7
<Document><CstmrPmtStsRpt>
<OrgnlGrpInfAndSts><OrgnlMsgId>MSG-43</OrgnlMsgId><GrpSts>PART</GrpSts></OrgnlGrpInfAndSts>
<OrgnlPmtInfAndSts>
<TxInfAndSts><OrgnlEndToEndId>E2E-1</OrgnlEndToEndId><TxSts>ACSC</TxSts></TxInfAndSts>
<TxInfAndSts><OrgnlEndToEndId>E2E-2</OrgnlEndToEndId><TxSts>RJCT</TxSts></TxInfAndSts>
</OrgnlPmtInfAndSts>
</CstmrPmtStsRpt></Document>
With a root path on Document.CstmrPmtStsRpt, check the group status, that the transaction statuses are ACSC and RJCT in order, and that the rejected transaction’s end-to-end id is E2E-2.
Hint
Closures work inside the getters too: getList("items.findAll { .. }.name", String.class). For the rejected transaction, use find { it.TxSts == 'RJCT' }, as in Check XML and HTML Responses in REST Assured.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
void businessCustomersAndARejectedPayment() {
JsonPath page = firstPageOfCustomers();
assertThat(page.getList("items.findAll { it.segment == 'BUSINESS' }.name", String.class))
.containsExactly("Bakkerij Bart B.V.");
String xml = """
<Document><CstmrPmtStsRpt>
<OrgnlGrpInfAndSts><OrgnlMsgId>MSG-43</OrgnlMsgId><GrpSts>PART</GrpSts></OrgnlGrpInfAndSts>
<OrgnlPmtInfAndSts>
<TxInfAndSts><OrgnlEndToEndId>E2E-1</OrgnlEndToEndId><TxSts>ACSC</TxSts></TxInfAndSts>
<TxInfAndSts><OrgnlEndToEndId>E2E-2</OrgnlEndToEndId><TxSts>RJCT</TxSts></TxInfAndSts>
</OrgnlPmtInfAndSts>
</CstmrPmtStsRpt></Document>
""";
XmlPath report = XmlPath.from(xml).setRootPath("Document.CstmrPmtStsRpt");
assertThat(report.getString("OrgnlGrpInfAndSts.GrpSts")).isEqualTo("PART");
assertThat(report.getList("OrgnlPmtInfAndSts.TxInfAndSts.TxSts", String.class)).containsExactly("ACSC", "RJCT");
assertThat(report.getString("OrgnlPmtInfAndSts.TxInfAndSts.find { it.TxSts == 'RJCT' }.OrgnlEndToEndId"))
.isEqualTo("E2E-2");
}
Summary
You built JsonPathAndXmlPathTest, which queries one page of customers as numbers, strings, lists, maps and records, and reads a webhook and a payment status report that never went over HTTP. No second JSON library joined the suite.
JsonPathandXmlPathare the path engines behindbody(..), available as objects.- Get one from a response with
extract().jsonPath(), or from any text withJsonPath.from(..)andXmlPath.from(..). - Typed getters such as
getInt(..)andgetString(..)convert the value to the type you ask for; a primitive getter on a missing value throws. getMap(..)returns an object as a map, andgetObject(..)andgetList(path, type)map objects to records with the object mapper.- Use them for many values from one response, and for JSON and XML that didn’t come from a REST Assured request; check single values in the chain with
body(..).
Here are the commands you used in this guide:
1
mvn test -pl module-04 -Dtest=JsonPathAndXmlPathTest
What’s Next
Next: continue with Map Responses to Java Records in REST Assured, which turns whole response bodies into records with as(..), including generic types such as Page<Customer>.
The code:
- The finished test class:
JsonPathAndXmlPathTest.java - The code and run commands for this module: Module 4 README
Go deeper:
- REST Assured Usage wiki, for
JsonPath,XmlPathand their configuration. - REST Assured javadoc, for every getter on
JsonPathandXmlPath. - AssertJ documentation, for the assertions used on the extracted values.
Related guides:
- Extract Values From a Response in REST Assured, for
extract().path(..)and why you validate first. - Filter JSON Lists With GPath in REST Assured, for the closures that also work inside the getters.
