JSONPATH RESPONSE EXTRACTION: PRIMITIVES, LISTS, MAPS & TYPE CASTING

Master programmatic JSON extraction in REST Assured: Standalone and inline JsonPath instances, extracting strongly typed primitives (getString, getInt, getBoolean, getDouble), multi-node List extraction, nested Map deserialization, root array handling, and JsonPathConfig type casting governance.

πŸ“‘ 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.

1. JsonPath Evaluation Engine & Type Mapping Architecture
The internal architectural topology of REST Assured's JsonPath parser, showing how wire strings and response byte buffers are translated into typed Java primitive and collection structures.
JsonPath Compilation & Java Type Mapping Topography
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β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: JsonPath in REST Assured is backed by Groovy's GPath engine. This architecture means JsonPath handles not only simple property reads, but also inline type-casting and null-safe evaluations without requiring a formal Java POJO class schema.
Real-Time Example 1: Direct Extraction from ValidatableResponse (.extract().path())
Extracting scalar primitive values directly from the terminal step of a Given-When-Then BDD pipeline using .then().extract().path().
Java (Terminal Inline BDD Path Extraction)
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!");
    }
}
Console Execution Output: GET /v1/students/STU-88219 -> HTTP 200 OK [114ms] [+] Extracted studentId directly: STU-88219 [+] Extracted enrolledCredits directly: 16 Terminal .extract().path() yields cleanly cast primitive objects.
Real-Time Example 2: Instantiating & Reusing Standalone JsonPath Objects
Eliminating duplicate network calls. Extracts the complete JsonPath instance from a single HTTP response or raw JSON string, querying multiple properties locally in memory.
Java (Standalone JsonPath Querying from Response & Raw String)
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);
    }
}
Standalone Parsing Output: GET /v1/students/STU-88219 [200 OK, 68ms] ---------------- PARSED CANDIDATE RECORD ---------------- Name : Nikita Sharma Email : nikita.sharma@nikita-infotech.com Credits : 16 GPA Score : 3.85 Is Active : true --------------------------------------------------------- [+] Parsed standalone string: Region=ap-south-1 | Healthy=true
Real-Time Example 3: Strongly Typed Primitives: getString, getInt, getLong & getDouble
Extracting numeric, boolean, and text values using strongly typed getters. Demonstrates how getInt(), getLong(), getDouble(), and getFloat() handle type casting from underlying JSON values.
Java (Strongly Typed Primitive Extraction)
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);
    }
}
Typed Primitive Extraction Trace: TxID=TXN-99412-PUNE | Invoices=3 | Epoch=1793614200000 | Balance=12500.5 | Tax=0.18 | Settled=false All values safely cast to target Java primitives without manual parsing.
Real-Time Example 4: Extracting JSON Arrays into Strongly Typed Lists (getList())
Extracting JSON array elements into Java List<T> collections. Demonstrates extracting untyped lists, strongly typed collections (List<String>, List<Integer>), and gathering nested property arrays across all elements.
Java (Extracting Arrays via getList())
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);
    }
}
List Extraction Telemetry: [*] Extracted Student IDs: [STU-88219, STU-88220, STU-88221] [*] Extracted Credits List: [16, 8, 12] [*] Courses for First Student: [API-PRO-101, REST-JAVA-201] JSON arrays projected into standard java.util.List collections.
Real-Time Example 5: Extracting Nested JSON Objects into Maps (getMap())
Deserializing JSON sub-objects into Java Map<String, Object> dictionaries. Useful for interrogating complex dynamic key-value pairs without creating a dedicated Java POJO class.
Java (Nested Object Extraction via getMap())
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");
    }
}
Map Extraction Output: ---------------- CONTACT MAP DESERIALIZATION ---------------- phone βž” +91-9876543210 city βž” Pune postalCode βž” 411015 country βž” India ------------------------------------------------------------- [*] Total student map objects extracted: 3 Nested object tree converted into java.util.Map key-value pairs.
Real-Time Example 6: Handling Root JSON Arrays ($ or empty path)
Navigating payloads where the root element is a JSON array ([...]) rather than a JSON object wrapper ({ "data": [...] }). Demonstrates using empty path "" or root symbol "$" to query elements.
Java (Root Array Parsing via empty path & bracket indexing)
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"));
    }
}
Root Array Output: GET /v1/tracks -> HTTP 200 OK [48ms] [*] Root Array total element count: 2 [+] Index [0] Track: ENTERPRISE_AUTOMATION [+] Index [1] Capacity: 25 [+] Projected All Codes: [ENTERPRISE_AUTOMATION, FULLSTACK_SDET] Root array accessed cleanly via empty string path "" and bracket indexers.
Real-Time Example 7: Configuring JsonPathConfig & Number Return Types
Customizing JsonPath parsing options. Configures JsonPathConfig to force floating-point numbers to return as BigDecimal instead of Float/Double to avoid rounding discrepancies in financial test suites.
Java (JsonPathConfig Tuning: BigDecimal & Double Allocation)
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"));
    }
}
Config Tuning Output: [Default] Class Type: java.lang.Double [Tuned] Class Type: java.math.BigDecimal [Tuned] Exact Value: 48921.8492019482 Eliminates floating-point rounding errors when asserting ledger balances.
Real-Time Example 8: Handling Null Values, Missing Keys & PathExceptions
Safeguarding JsonPath extractions against null pointers. Demonstrates how JsonPath evaluates missing attributes (returning null) versus malformed syntax paths (throwing JsonPathException), and using fallback defaults.
Java (Null Safety, Missing Key Handling & Exception Triage)
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");
    }
}
Null Safety Output: [*] 'notes' property value: null [*] Missing key property value: null [*] Resolved notes with fallback: DEFAULT_EMPTY_NOTE Querying absent keys safely evaluates to null without throwing NullPointerExceptions.
Real-Time Example 9: JsonPath Method Specification Reference Matrix
A comprehensive reference summary pairing JsonPath methods, return types, path expressions, and operational best practices for REST Assured engineers.
JsonPath Method Specification Reference Matrix
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.     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: JsonPath provides the critical bridge between network transport and Java business logic. By extracting full JsonPath instances to read multiple properties in-memory, leveraging typed primitive getters, and handling root arrays cleanly, you build efficient, readable, and maintainable automated API workflows.