ποΈ Object Graph Modeling, Composite Trees & Generic Envelope Architecture
Real-world enterprise APIs rarely return flat, single-tier JSON structures with only primitive scalar properties. Production payloads feature deeply nested composite object graphsβsuch as an order entity containing customer sub-objects, dynamic billing address dictionaries, and arrays of child line items. In Java test automation, attempting to model these structures using generic untyped maps leads to brittle type casting and maintenance overhead. By designing hierarchical nested POJOs, test architects break down complex JSON structures into modular, reusable components (such as AddressDTO, CourseRegistration, ContactInfo). Furthermore, by coupling these child models with generic wrapper envelopes (ApiResponse<T>) and preserving runtime type signatures via TypeRef, REST Assured test suites achieve complete compile-time type safety, effortless serialization on outbound requests, and clean fluent assertions on inbound responses.
JAVA OBJECT GRAPH COMPOSITION MODEL βββΊ REST ASSURED WIRE JSON PAYLOAD:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ROOT GENERIC ENVELOPE: ApiResponse<StudentEnrollmentAggregate> β
β βββ String status; β
β βββ String message; β
β βββ T data; ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TARGET AGGREGATE POJO: StudentEnrollmentAggregate β
β βββ String studentId; β
β βββ String fullName; β
β βββ ContactInformation contact; (1-to-1 POJO Composition) ββββββββββββββββ β
β βββ List<CourseEnrollment> courses; (1-to-Many Collection) βββββββββββββββΌββββββββββββββββββββ
β βββ Map<String, Object> customMetadata; (Dynamic Key-Value Map) ββββββββββΌββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββΌββββ
β β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
βΌ β β
ββββββββββββββββββββββββββββββββββββββββββββββββ β β
β CHILD POJO: ContactInformation β β β
β βββ String primaryPhone; β β β
β βββ String primaryEmail; β β β
β βββ AddressModel physicalAddress; βββββββββββΌββββββββββββββββββββββββββ β β
ββββββββββββββββββββββββββββββββββββββββββββββββ β β β
βΌ β β
ββββββββββββββββββββββββββββββββββββ β β
β LEAF POJO: AddressModel β β β
β βββ String streetAddress; β β β
β βββ String city; ("Pune") β β β
β βββ String postalCode; β β β
ββββββββββββββββββββββββββββββββββββ β β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βΌ β
ββββββββββββββββββββββββββββββββββββββββββββββββ β
β CHILD COLLECTION POJO: CourseEnrollment β β
β βββ String courseCode; ("REST-JAVA-201") β β
β βββ String courseTitle; β β
β βββ int credits; (4) β β
ββββββββββββββββββββββββββββββββββββββββββββββββ β
β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ
β EMBEDDED MAP: customMetadata β
β βββ "tenantRegion" βββΊ "MH-PUNE-WEST" β
β βββ "isScholarshipEligible" βββΊ true β
ββββββββββββββββββββββββββββββββββββββββββββββββ
AddressDTO leaf model and embeds it inside a ContactDetailsDTO child model, which is then composed within the root CandidateRegistrationRequest POJO.
package com.nikita.restassured.models.composition;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
// 1. LEAF OBJECT MODEL: AddressDTO
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class AddressDTO {
@JsonProperty("street")
private String street;
@JsonProperty("city")
private String city;
@JsonProperty("state")
private String state;
@JsonProperty("postalCode")
private String postalCode;
public AddressDTO() {}
public AddressDTO(String street, String city, String state, String postalCode) {
this.street = street;
this.city = city;
this.state = state;
this.postalCode = postalCode;
}
public String getStreet() { return street; }
public String getCity() { return city; }
public String getState() { return state; }
public String getPostalCode() { return postalCode; }
}
// 2. INTERMEDIATE CHILD OBJECT MODEL: ContactDetailsDTO
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class ContactDetailsDTO {
@JsonProperty("phone")
private String phone;
@JsonProperty("email")
private String email;
@JsonProperty("permanentAddress")
private AddressDTO permanentAddress; // 1-to-1 POJO Composition!
public ContactDetailsDTO() {}
public ContactDetailsDTO(String phone, String email, AddressDTO permanentAddress) {
this.phone = phone;
this.email = email;
this.permanentAddress = permanentAddress;
}
public String getPhone() { return phone; }
public String getEmail() { return email; }
public AddressDTO getPermanentAddress() { return permanentAddress; }
}
// 3. ROOT AGGREGATE MODEL: CandidateRegistrationRequest
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CandidateRegistrationRequest {
@JsonProperty("fullName")
private String fullName;
@JsonProperty("academicTrack")
private String academicTrack;
@JsonProperty("contact")
private ContactDetailsDTO contact; // 1-to-1 POJO Composition!
public CandidateRegistrationRequest() {}
public CandidateRegistrationRequest(String fullName, String academicTrack, ContactDetailsDTO contact) {
this.fullName = fullName;
this.academicTrack = academicTrack;
this.contact = contact;
}
public String getFullName() { return fullName; }
public String getAcademicTrack() { return academicTrack; }
public ContactDetailsDTO getContact() { return contact; }
}
List<CourseModuleDTO> inside a parent course catalog class to manage ordered child collections.
package com.nikita.restassured.models.collections;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
// Child Model inside Collection
@JsonIgnoreProperties(ignoreUnknown = true)
class CourseModuleDTO {
@JsonProperty("moduleCode")
private String moduleCode;
@JsonProperty("moduleTitle")
private String moduleTitle;
@JsonProperty("credits")
private int credits;
public CourseModuleDTO() {}
public CourseModuleDTO(String moduleCode, String moduleTitle, int credits) {
this.moduleCode = moduleCode;
this.moduleTitle = moduleTitle;
this.credits = credits;
}
public String getModuleCode() { return moduleCode; }
public String getModuleTitle() { return moduleTitle; }
public int getCredits() { return credits; }
}
// Parent Aggregate holding Collection of Child POJOs
@JsonIgnoreProperties(ignoreUnknown = true)
public class CurriculumPlanDTO {
@JsonProperty("curriculumId")
private String curriculumId;
@JsonProperty("trackName")
private String trackName;
// 1-to-Many Collection: Typed List of Child POJOs
@JsonProperty("modules")
private List<CourseModuleDTO> modules = new ArrayList<>();
public CurriculumPlanDTO() {}
public CurriculumPlanDTO(String curriculumId, String trackName, List<CourseModuleDTO> modules) {
this.curriculumId = curriculumId;
this.trackName = trackName;
this.modules = modules;
}
public String getCurriculumId() { return curriculumId; }
public String getTrackName() { return trackName; }
public List<CourseModuleDTO> getModules() { return modules; }
// Fluent helper method for adding items cleanly
public void addModule(CourseModuleDTO module) {
this.modules.add(module);
}
}
package com.nikita.restassured.nested;
import com.nikita.restassured.models.collections.CurriculumPlanDTO;
import com.nikita.restassured.models.collections.CourseModuleDTO;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class CompositeSerializationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Assemble 3-tier object graph and serialize in POST request")
public void testDeepCompositePojoSerialization() {
// Step 1: Construct Child Collection Elements
CourseModuleDTO mod1 = new CourseModuleDTO("REST-JAVA-201", "REST Assured Fundamentals", 4);
CourseModuleDTO mod2 = new CourseModuleDTO("DOCKER-QA-301", "Containerized API Testing", 3);
List<CourseModuleDTO> moduleList = Arrays.asList(mod1, mod2);
// Step 2: Construct Parent Aggregate Model
CurriculumPlanDTO plan = new CurriculumPlanDTO(
"CURR-AUTOMATION-2026",
"Enterprise SDET Mastery",
moduleList
);
// Step 3: Dispatch in Given phase; Jackson serializes complete nested tree
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.header("X-Tenant-Key", "MAHARASHTRA_PUNE_01")
.body(plan)
.log().body()
.when()
.post("/curriculum/plans")
.then()
.statusCode(201)
.body("status", equalTo("PLAN_PROVISIONED"))
.body("data.curriculumId", equalTo("CURR-AUTOMATION-2026"))
.body("data.modules", hasSize(2))
.body("data.modules[0].moduleCode", equalTo("REST-JAVA-201"))
.body("data.modules.credits.sum()", equalTo(7));
System.out.println("[β] Deep composite object graph serialized and verified successfully.");
}
}
ApiResponse<T> model that encapsulates common envelope fields (status, message, timestamp) around any domain payload type.
package com.nikita.restassured.models.generic;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Instant;
// Universal Generic Response Envelope
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse<T> {
@JsonProperty("status")
private String status;
@JsonProperty("message")
private String message;
@JsonProperty("timestamp")
private String timestamp;
// Generic payload type: Holds any domain entity (Student, Order, List, etc.)
@JsonProperty("data")
private T data;
public ApiResponse() {}
public ApiResponse(String status, String message, T data) {
this.status = status;
this.message = message;
this.timestamp = Instant.now().toString();
this.data = data;
}
public String getStatus() { return status; }
public String getMessage() { return message; }
public String getTimestamp() { return timestamp; }
public T getData() { return data; }
}
TypeRef with ApiResponse<StudentSummaryDTO> and ApiResponse<List<StudentSummaryDTO>> to maintain complete type safety.
package com.nikita.restassured.nested;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.nikita.restassured.models.generic.ApiResponse;
import io.restassured.common.mapper.TypeRef;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
@JsonIgnoreProperties(ignoreUnknown = true)
class StudentSummaryDTO {
@JsonProperty("id")
private String id;
@JsonProperty("fullName")
private String fullName;
public StudentSummaryDTO() {}
public String getId() { return id; }
public String getFullName() { return fullName; }
}
public class GenericEnvelopeDeserializationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Deserialize single entity wrapped inside generic ApiResponse")
public void testGenericSingleEntityEnvelope() {
// Deserializing into ApiResponse
ApiResponse<StudentSummaryDTO> envelope = given()
.baseUri(BASE_URI)
.pathParam("id", "STU-88219")
.when()
.get("/students/{id}")
.then()
.statusCode(200)
.extract()
// TypeRef captures the parameterized type: ApiResponse
.as(new TypeRef<ApiResponse<StudentSummaryDTO>>() {});
System.out.println("[+] Envelope Status : " + envelope.getStatus());
System.out.println("[+] Entity FullName : " + envelope.getData().getFullName());
Assert.assertEquals(envelope.getStatus(), "SUCCESS");
Assert.assertEquals(envelope.getData().getId(), "STU-88219");
}
@Test(description = "Deserialize collection of entities wrapped inside generic ApiResponse>")
public void testGenericCollectionEnvelope() {
// Deserializing into ApiResponse>
ApiResponse<List<StudentSummaryDTO>> listEnvelope = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract()
// TypeRef preserves nested generic collection signature:
.as(new TypeRef<ApiResponse<List<StudentSummaryDTO>>>() {});
List<StudentSummaryDTO> studentList = listEnvelope.getData();
System.out.println("[*] Total students in unwrapped envelope list: " + studentList.size());
Assert.assertFalse(studentList.isEmpty());
Assert.assertEquals(studentList.get(0).getId(), "STU-88219");
}
}
Map<String, Object> inside a structured POJO to support custom attributes, tenant metadata, or extensible tag dictionaries.
package com.nikita.restassured.models.hybrid;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.restassured.http.ContentType;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@JsonIgnoreProperties(ignoreUnknown = true)
class ExtensibleStudentRequest {
@JsonProperty("studentId")
private String studentId;
@JsonProperty("fullName")
private String fullName;
// Dynamic key-value dictionary for dynamic metadata
private Map<String, Object> dynamicAttributes = new HashMap<>();
public ExtensibleStudentRequest() {}
public ExtensibleStudentRequest(String studentId, String fullName) {
this.studentId = studentId;
this.fullName = fullName;
}
public String getStudentId() { return studentId; }
public String getFullName() { return fullName; }
// @JsonAnyGetter unwraps map entries directly into the root JSON body during serialization
@JsonAnyGetter
public Map<String, Object> getDynamicAttributes() {
return dynamicAttributes;
}
// @JsonAnySetter captures unrecognized JSON properties into the map during deserialization
@JsonAnySetter
public void setDynamicAttribute(String key, Object value) {
this.dynamicAttributes.put(key, value);
}
}
public class HybridMapEmbeddingTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Serialize POJO with dynamic unwrapped attributes using @JsonAnyGetter")
public void testSerializeDynamicProperties() {
ExtensibleStudentRequest student = new ExtensibleStudentRequest("STU-88219", "Nikita Sharma");
student.setDynamicAttribute("preferredLanguage", "Marathi");
student.setDynamicAttribute("scholarshipCode", "SCHOLAR-PUNE-2026");
student.setDynamicAttribute("seatNumber", 42);
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.body(student)
.log().body()
.when()
.post("/students/extensible")
.then()
.statusCode(201)
.body("status", equalTo("SUCCESS"))
.body("data.preferredLanguage", equalTo("Marathi"))
.body("data.seatNumber", equalTo(42));
System.out.println("[β] Extensible POJO with dynamic attributes serialized cleanly.");
}
}
package com.nikita.restassured.nested;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.assertj.core.api.Assertions;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
// Deeply nested hierarchy definitions
@JsonIgnoreProperties(ignoreUnknown = true)
class OrganizationNode {
public String orgCode;
public DepartmentNode department;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class DepartmentNode {
public String deptName;
public List<TeamNode> teams;
}
@JsonIgnoreProperties(ignoreUnknown = true)
class TeamNode {
public String teamLead;
public int engineerCount;
}
public class DeepHierarchyValidationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Traverse 3-level deserialized POJO hierarchy and evaluate AssertJ conditions")
public void testDeepHierarchyAssertion() {
OrganizationNode org = given()
.baseUri(BASE_URI)
.when()
.get("/organizations/NIKITA-INFOTECH")
.then()
.statusCode(200)
.extract()
.as(OrganizationNode.class);
// Assert parent node attributes
Assertions.assertThat(org.orgCode)
.as("Organization code must match")
.isEqualTo("NIKITA-INFOTECH");
// Assert child node attributes
Assertions.assertThat(org.department.deptName)
.as("Department name check")
.isEqualTo("QA_AUTOMATION_CORE");
// Assert grandchild collection attributes
Assertions.assertThat(org.department.teams)
.as("Department must contain active engineering teams")
.isNotEmpty()
.hasSize(2)
.extracting(team -> team.teamLead)
.contains("Nikita Sharma");
// Sum across grandchild nodes
int totalEngineers = org.department.teams.stream()
.mapToInt(team -> team.engineerCount)
.sum();
Assertions.assertThat(totalEngineers)
.as("Total department headcount across teams")
.isGreaterThanOrEqualTo(10);
System.out.println("[β] Deep object hierarchy (Organization β Department β Teams) validated cleanly.");
}
}
JsonMappingException: Infinite recursion (StackOverflowError) in bidirectional parent-child POJO models using @JsonManagedReference and @JsonBackReference.
package com.nikita.restassured.models.recursion;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
// ==============================================================================
// PROBLEM: Bidirectional references cause infinite recursion during serialization!
// Parent references Child, and Child references Parent back:
// Parent βββΊ Child βββΊ Parent βββΊ Child βββΊ StackOverflowError!
//
// SOLUTION:
// @JsonManagedReference: Placed on the parent forward collection
// @JsonBackReference: Placed on the child back-pointer (omitted during serialization)
// ==============================================================================
class ClassroomBatch {
public String batchName;
// @JsonManagedReference tells Jackson to serialize this forward child collection
@JsonManagedReference
public List<EnrolledStudent> students = new ArrayList<>();
public ClassroomBatch(String batchName) {
this.batchName = batchName;
}
}
class EnrolledStudent {
public String studentName;
// @JsonBackReference tells Jackson to skip serializing this back-pointer, breaking the loop!
@JsonBackReference
public ClassroomBatch batch;
public EnrolledStudent(String studentName, ClassroomBatch batch) {
this.studentName = studentName;
this.batch = batch;
}
}
public class CircularReferenceTriageTest {
@Test(description = "Verify circular reference annotations prevent serialization StackOverflowError")
public void testResolveCircularRecursion() throws Exception {
// Setup bidirectional relationship
ClassroomBatch batch = new ClassroomBatch("PUNE_AUTOMATION_2026");
EnrolledStudent student1 = new EnrolledStudent("Nikita Sharma", batch);
batch.students.add(student1);
// Serialize using Jackson
ObjectMapper mapper = new ObjectMapper();
String jsonResult = mapper.writeValueAsString(batch);
System.out.println("[*] Serialized cleanly without recursion: " + jsonResult);
Assert.assertTrue(jsonResult.contains("PUNE_AUTOMATION_2026"));
Assert.assertTrue(jsonResult.contains("Nikita Sharma"));
Assert.assertFalse(jsonResult.contains("batchName\":\"PUNE_AUTOMATION_2026\",\"students\":[{\"studentName\":\"Nikita Sharma\",\"batch\":{\"batchName\""));
}
}
NESTED POJO & COLLECTION SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β STRUCTURAL CONSTRUCT β ANNOTATION / DIRECTIVE β TARGET PLACEMENT β PRIMARY OPERATIONAL ROLE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β 1-to-1 POJO Composition β Inner POJO field declaration β Parent Class β Models nested object trees β
β 1-to-Many Collections β List<ChildPOJO> / Set<Child> β Parent Class β Models child object arrays β
β Generic Envelope Model β class ApiResponse<T> β Root Class β Reusable envelope wrapper β
β Generic Deserialization β new TypeRef<ApiResponse<T>> β .as(TypeRef) β Preserves generic types β
β Root-Level Array Model β TargetPOJO[].class β .as(Target[].cls)β Deserializes top-level arrays β
β Dynamic Metadata Map β Map<String, Object> β POJO Field β Dynamic key-value pairs β
β Unwrapped Map Entries β @JsonAnyGetter β Map Getter β Flattens map into root JSON β
β Dynamic Inbound Catch β @JsonAnySetter β Map Setter Methodβ Ingests unknown keys to map β
β Circular Reference Breakβ @JsonManagedReference β Forward Parent β Serializes forward child list β
β Circular Back-Pointer β @JsonBackReference β Backward Child β Skips back-pointer to avoid SOβ
β Tolerant Inbound Mappingβ @JsonIgnoreProperties(ign..) β Class Level β Discards unexpected keys β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 NESTED POJO & COLLECTION BEST PRACTICES: β
β 1. Model child concepts as modular POJOs: Break large schemas into reusable classes (Address, Contact). β
β 2. Use TypeRef for generic envelopes: Prevent ClassCastExceptions when unmarshalling ApiResponse<T>. β
β 3. Prevent circular StackOverflowErrors: Use @JsonManagedReference and @JsonBackReference on loops. β
β 4. Leverage @JsonAnyGetter for extensible schemas: Flatten dynamic key-value dictionaries cleanly. β
β 5. Deserialize root arrays with POJO array types: Use Target[].class and convert to List via Arrays. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ