π Programmatic Data Unpacking, Wire Navigation & Downstream Chaining
While fluent inline BDD assertions (.body("path", matcher)) provide immediate verification within the test chain, automated testing workflows frequently require extracting values out of response envelopes into strongly typed Java memory. Whether extracting dynamic OAuth bearer tokens, database entity UUIDs, or transactional correlation IDs to feed subsequent HTTP requests, manual string manipulation and regex scraping are brittle. REST Assured's JsonPath engine (io.restassured.path.json.JsonPath) provides an expressive path navigation engine that evaluates dot-notation paths against complex JSON trees. By mastering typed getters such as getString(), getInt(), getList(), and getMap()βalongside standalone parsing of raw wire stringsβautomation engineers eliminate verbose parsing boilerplate and bridge end-to-end multi-endpoint test workflows.
RAW JSON RESPONSE STREAM (Wire Octets / UTF-8 String):
{
"status": "SUCCESS",
"data": {
"studentId": "STU-88219",
"enrolledCredits": 16,
"gpa": 3.85,
"isActive": true,
"contact": { "city": "Pune", "zip": "411015" },
"courses": ["REST-JAVA-201", "DOCKER-QA-301"]
}
}
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JSONPATH PARSER ENGINE (io.restassured.path.json.JsonPath / Groovy AST Compiler) β
β βββ 1. Dot-Notation Traverser: Resolves object hierarchies ("data.contact.city") β
β βββ 2. Bracket Indexer: Accesses array elements ("data.courses[0]") β
β βββ 3. JsonPathConfig Parser: Configures Jackson / Gson / Johnzon deserializer defaults β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββ
βΌ βΌ βΌ
ββββββββββββββββββββββββ ββββββββββββββββββββββββ ββββββββββββββββββββββββ
β TYPED PRIMITIVES β β TYPED COLLECTIONS β β STRUCTURED MAPS β
ββββββββββββββββββββββββ€ ββββββββββββββββββββββββ€ ββββββββββββββββββββββββ€
β β’ getString(...) β β β’ getList(...) β β β’ getMap(...) β
β β’ getInt(...) β β β’ getList("..", Cls) β β β’ getJsonObject(...) β
β β’ getDouble(...) β β β’ getList().size() β β β’ Map<String, Object>β
β β’ getBoolean(...) β β β’ List<String> β β β’ Nested Dictionariesβ
ββββββββββββββββββββββββ ββββββββββββββββββββββββ ββββββββββββββββββββββββ
.then().extract().path().
package com.nikita.restassured.jsonpath;
import io.restassured.http.ContentType;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class InlinePathExtractionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Extract single path values directly out of the BDD assertion chain")
public void testDirectBddPathExtraction() {
// Step 1: Execute GET and extract scalar string directly from terminal step
String extractedStudentId = given()
.baseUri(BASE_URI)
.accept(ContentType.JSON)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
// Terminal transition: extract target path directly
.extract()
.path("data.id");
System.out.println("[+] Extracted studentId directly: " + extractedStudentId);
Assert.assertEquals(extractedStudentId, "STU-88219", "Mismatch in extracted student ID!");
// Step 2: Extract an integer value directly
int enrolledCredits = given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.extract()
.path("data.enrolledCredits");
System.out.println("[+] Extracted enrolledCredits directly: " + enrolledCredits);
Assert.assertTrue(enrolledCredits >= 4, "Credits must be at least 4!");
}
}
JsonPath instance from a single HTTP response or raw JSON string, querying multiple properties locally in memory.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
public class StandaloneJsonPathTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Extract JsonPath instance from Response to query multiple paths in memory")
public void testReusableJsonPathFromResponse() {
// Issue single network call and convert response payload to JsonPath instance
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.extract()
.jsonPath();
// Query multiple fields in-memory without repeating HTTP transactions:
String candidateName = jsonPath.getString("data.fullName");
String candidateEmail = jsonPath.getString("data.email");
int totalCredits = jsonPath.getInt("data.enrolledCredits");
double gpaScore = jsonPath.getDouble("data.gpa");
boolean isActive = jsonPath.getBoolean("data.isActive");
System.out.println("---------------- PARSED CANDIDATE RECORD ----------------");
System.out.println(" Name : " + candidateName);
System.out.println(" Email : " + candidateEmail);
System.out.println(" Credits : " + totalCredits);
System.out.println(" GPA Score : " + gpaScore);
System.out.println(" Is Active : " + isActive);
System.out.println("---------------------------------------------------------");
Assert.assertEquals(candidateName, "Nikita Sharma");
Assert.assertEquals(totalCredits, 16);
Assert.assertTrue(isActive);
}
@Test(description = "Instantiate standalone JsonPath parser from raw JSON string")
public void testJsonPathFromRawString() {
String staticRawJson = "{\n" +
" \"gateway\": \"NGINX_INGRESS_01\",\n" +
" \"cluster\": { \"region\": \"ap-south-1\", \"zone\": \"pune-a\" },\n" +
" \"healthy\": true\n" +
"}";
// Parse arbitrary string directly using static factory or constructor
JsonPath rawParser = new JsonPath(staticRawJson);
String region = rawParser.getString("cluster.region");
boolean isHealthy = rawParser.getBoolean("healthy");
System.out.println("[+] Parsed standalone string: Region=" + region + " | Healthy=" + isHealthy);
Assert.assertEquals(region, "ap-south-1");
Assert.assertTrue(isHealthy);
}
}
getInt(), getLong(), getDouble(), and getFloat() handle type casting from underlying JSON values.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
public class TypedPrimitiveExtractionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Demonstrate strongly-typed primitive getters across numerical and textual nodes")
public void testTypedPrimitiveGetters() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219/financial-ledger")
.then()
.statusCode(200)
.extract()
.jsonPath();
// 1. Text extraction
String transactionId = jsonPath.getString("ledger.transactionId");
// 2. Integer extraction (32-bit signed)
int invoiceCount = jsonPath.getInt("ledger.totalInvoices");
// 3. Long extraction (64-bit epoch timestamp or high-precision ID)
long createdEpochMs = jsonPath.getLong("ledger.createdTimestampEpoch");
// 4. Double extraction (64-bit floating-point currency / balance)
double totalBalanceDue = jsonPath.getDouble("ledger.balanceDue");
// 5. Float extraction (32-bit floating-point percentage)
float taxRate = jsonPath.getFloat("ledger.applicableTaxRate");
// 6. Boolean extraction
boolean isSettled = jsonPath.getBoolean("ledger.isSettled");
System.out.println("TxID=" + transactionId + " | Invoices=" + invoiceCount +
" | Epoch=" + createdEpochMs + " | Balance=" + totalBalanceDue +
" | Tax=" + taxRate + " | Settled=" + isSettled);
Assert.assertNotNull(transactionId);
Assert.assertTrue(createdEpochMs > 1700000000000L);
Assert.assertEquals(totalBalanceDue, 12500.50, 0.01);
}
}
List<T> collections. Demonstrates extracting untyped lists, strongly typed collections (List<String>, List<Integer>), and gathering nested property arrays across all elements.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
public class ListExtractionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Extract array properties into Java List collections")
public void testExtractJsonArraysToLists() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract()
.jsonPath();
// =====================================================================
// TECHNIQUE A: GATHER SPECIFIC PROPERTY ACROSS ALL OBJECTS IN ARRAY
// Expression 'data.id' projects all 'id' fields into a List
// =====================================================================
List<String> allStudentIds = jsonPath.getList("data.id");
System.out.println("[*] Extracted Student IDs: " + allStudentIds);
Assert.assertTrue(allStudentIds.contains("STU-88219"));
// =====================================================================
// TECHNIQUE B: STRONGLY-TYPED LIST EXTRACTION (EXPLICIT CLASS ARGUMENT)
// getList(path, genericTypeClass) guarantees type safety:
// =====================================================================
List<Integer> allCreditValues = jsonPath.getList("data.enrolledCredits", Integer.class);
System.out.println("[*] Extracted Credits List: " + allCreditValues);
Assert.assertFalse(allCreditValues.isEmpty());
// =====================================================================
// TECHNIQUE C: EXTRACT SIMPLE PRIMITIVE ARRAY
// Expression 'courses' targets a simple string array: ["API-101", "QA-201"]
// =====================================================================
List<String> firstStudentCourses = jsonPath.getList("data[0].enrolledCourseCodes", String.class);
System.out.println("[*] Courses for First Student: " + firstStudentCourses);
Assert.assertEquals(firstStudentCourses.size(), 2);
}
}
Map<String, Object> dictionaries. Useful for interrogating complex dynamic key-value pairs without creating a dedicated Java POJO class.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
public class MapExtractionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Extract nested JSON sub-object into Java Map dictionary")
public void testExtractNestedObjectToMap() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.extract()
.jsonPath();
// 1. Extract single nested object 'contactInfo' into a Map
Map<String, Object> contactMap = jsonPath.getMap("data.contactInfo");
System.out.println("---------------- CONTACT MAP DESERIALIZATION ----------------");
contactMap.forEach((key, val) -> System.out.println(" " + key + " β " + val));
System.out.println("-------------------------------------------------------------");
Assert.assertEquals(contactMap.get("city"), "Pune");
Assert.assertEquals(contactMap.get("postalCode"), "411015");
// 2. Extract an array of JSON objects into a List of Maps: List>
List<Map<String, Object>> allStudentsAsMaps = jsonPath.getList("data", (Class) Map.class);
System.out.println("[*] Total student map objects extracted: " + allStudentsAsMaps.size());
Map<String, Object> firstStudent = allStudentsAsMaps.get(0);
Assert.assertEquals(firstStudent.get("id"), "STU-88219");
}
}
[...]) rather than a JSON object wrapper ({ "data": [...] }). Demonstrates using empty path "" or root symbol "$" to query elements.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
public class RootArrayExtractionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Extract from payloads where root element is a JSON array")
public void testRootArrayExtraction() {
// Assume /v1/tracks returns a raw JSON array:
// [
// { "code": "ENTERPRISE_AUTOMATION", "capacity": 30 },
// { "code": "FULLSTACK_SDET", "capacity": 25 }
// ]
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/tracks")
.then()
.statusCode(200)
.extract()
.jsonPath();
// =====================================================================
// TECHNIQUE A: EMPTY PATH "" OR ROOT "$" TARGETS ENTIRE ROOT ARRAY
// =====================================================================
List<Map<String, Object>> rootArray = jsonPath.getList("");
System.out.println("[*] Root Array total element count: " + rootArray.size());
Assert.assertEquals(rootArray.size(), 2);
// =====================================================================
// TECHNIQUE B: DIRECT BRACKET INDEXING ON ROOT ARRAY: [0], [1]
// =====================================================================
String firstTrackCode = jsonPath.getString("[0].code");
int secondTrackCapacity = jsonPath.getInt("[1].capacity");
System.out.println("[+] Index [0] Track: " + firstTrackCode);
System.out.println("[+] Index [1] Capacity: " + secondTrackCapacity);
Assert.assertEquals(firstTrackCode, "ENTERPRISE_AUTOMATION");
Assert.assertEquals(secondTrackCapacity, 25);
// =====================================================================
// TECHNIQUE C: PROPERTY PROJECTION FROM ROOT ARRAY: code, capacity
// =====================================================================
List<String> allCodes = jsonPath.getList("code");
System.out.println("[+] Projected All Codes: " + allCodes);
Assert.assertTrue(allCodes.contains("FULLSTACK_SDET"));
}
}
JsonPathConfig to force floating-point numbers to return as BigDecimal instead of Float/Double to avoid rounding discrepancies in financial test suites.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import io.restassured.path.json.config.JsonPathConfig;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.math.BigDecimal;
public class JsonPathConfigTuningTest {
@Test(description = "Configure JsonPath to parse floating-point decimals as BigDecimal for precision")
public void testBigDecimalParsing() {
String financialJson = "{\n" +
" \"accountNumber\": \"AC-9941284\",\n" +
" \"exactPrincipal\": 48921.8492019482,\n" +
" \"currency\": \"INR\"\n" +
"}";
// =====================================================================
// DEFAULT BEHAVIOR: Returns Double (Prone to IEEE 754 precision loss)
// =====================================================================
JsonPath defaultJsonPath = new JsonPath(financialJson);
Object defaultPrincipal = defaultJsonPath.get("exactPrincipal");
System.out.println("[Default] Class Type: " + defaultPrincipal.getClass().getName());
Assert.assertTrue(defaultPrincipal instanceof Double);
// =====================================================================
// TUNED BEHAVIOR: Use JsonPathConfig.numberReturnType(BIG_DECIMAL)
// Guarantees zero precision loss on financial / accounting metrics:
// =====================================================================
JsonPathConfig bigDecimalConfig = new JsonPathConfig()
.numberReturnType(JsonPathConfig.NumberReturnType.BIG_DECIMAL);
JsonPath tunedJsonPath = new JsonPath(financialJson).using(bigDecimalConfig);
BigDecimal precisePrincipal = tunedJsonPath.get("exactPrincipal");
System.out.println("[Tuned] Class Type: " + precisePrincipal.getClass().getName());
System.out.println("[Tuned] Exact Value: " + precisePrincipal.toPlainString());
Assert.assertEquals(precisePrincipal, new BigDecimal("48921.8492019482"));
}
}
null) versus malformed syntax paths (throwing JsonPathException), and using fallback defaults.
package com.nikita.restassured.jsonpath;
import io.restassured.path.json.JsonPath;
import io.restassured.path.json.exception.JsonPathException;
import org.testng.Assert;
import org.testng.annotations.Test;
public class JsonPathNullSafetyTest {
@Test(description = "Verify behavior when querying non-existent keys vs explicit nulls")
public void testMissingKeysAndNullSafety() {
String testJson = "{\n" +
" \"studentId\": \"STU-88219\",\n" +
" \"notes\": null\n" +
"}";
JsonPath jsonPath = new JsonPath(testJson);
// 1. Explicit null value in JSON returns Java null:
String notesValue = jsonPath.getString("notes");
System.out.println("[*] 'notes' property value: " + notesValue);
Assert.assertNull(notesValue, "Field with null value must return null!");
// 2. Non-existent key in JSON also returns Java null (Does not throw exception):
String nonExistentField = jsonPath.getString("nonExistentProperty");
System.out.println("[*] Missing key property value: " + nonExistentField);
Assert.assertNull(nonExistentField, "Missing key should safely return null!");
// 3. Fallback pattern using Java 8 Optional or ternary operator:
String resolvedNotes = (notesValue != null) ? notesValue : "DEFAULT_EMPTY_NOTE";
System.out.println("[*] Resolved notes with fallback: " + resolvedNotes);
Assert.assertEquals(resolvedNotes, "DEFAULT_EMPTY_NOTE");
}
@Test(expectedExceptions = JsonPathException.class,
description = "Demonstrate JsonPathException thrown on broken GPath syntax")
public void testMalformedPathThrowsException() {
String sampleJson = "{\"status\": \"OK\"}";
JsonPath jsonPath = new JsonPath(sampleJson);
// Syntactically invalid GPath (unclosed bracket)
jsonPath.get("data[invalid-syntax-bracket");
}
}
JSONPATH METHOD SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β JSONPATH METHOD β PATH EXPRESSION SYNTAX β JAVA RETURN TYPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β getString(path) β "data.email" β java.lang.String β Extracts string scalar value β
β getInt(path) β "data.enrolledCredits" β int / Integer β Extracts 32-bit signed integerβ
β getLong(path) β "data.createdTimestampEpoch" β long / Long β Extracts 64-bit signed integerβ
β getDouble(path) β "data.gpa" β double / Double β Extracts 64-bit float decimal β
β getFloat(path) β "data.taxRate" β float / Float β Extracts 32-bit float decimal β
β getBoolean(path) β "data.isActive" β boolean / Booleanβ Extracts boolean true/false β
β getList(path) β "data.id" β List<?> β Extracts array or projections β
β getList(path, Class<T>) β "data.id", String.class β List<T> β Strongly-typed list projectionβ
β getMap(path) β "data.contactInfo" β Map<String, Obj> β Deserializes object to Map β
β getJsonObject(path) β "data.contactInfo" β T (Generic Objectβ Untyped generic object getter β
β getList("") β "" (Empty string or "$") β List<?> β Targets root-level JSON array β
β Bracket Indexer [i] β "[0].code" / "data[0].id" β Target Node Type β Array index-based navigation β
β JsonPathConfig β .using(new JsonPathConfig()) β JsonPath instanceβ Configures BigDecimal return β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 JSONPATH EXTRACTION BEST PRACTICES: β
β 1. Extract a single JsonPath instance: Parse once in memory when querying multiple fields on a payload. β
β 2. Use typed getters (getInt, getDouble): Avoid manual String-to-number casting boilerplate in tests. β
β 3. Pass generic type class to getList: Use getList("path", String.class) for compile-time safety. β
β 4. Target root arrays with empty path "": Use getList("") or bracket indexers like "[0]" for root lists. β
β 5. Use BigDecimal config for financial tests: Avoid IEEE 754 precision loss on high-precision floats. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ