π§± Type-Safe Model Architecture & Automated Outbound Marshaling
Hardcoding raw JSON string payloads inside automated test scripts creates brittle, unmaintainable test code. Escaping double quotes, managing syntax typos, and handling schema drift manually leads to fragile tests that break whenever API fields change. Java POJO (Plain Old Java Object) Serialization introduces strong typing and object-oriented modeling into REST Assured pipelines. By defining model classes with standard fields, getters, setters, and Jackson annotations, developers pass Java object instances directly into .body(pojoInstance). Under the hood, REST Assured scans the JVM classpath, discovers Jackson Databind or Google Gson, and automatically marshals the Java memory state into an RFC-compliant JSON wire string. Understanding Jackson annotations, custom serializers, null exclusion rules, and explicit ObjectMapperType selection is essential for building scalable, clean test automation architectures.
REST ASSURED AUTOMATIC SERIALIZATION ENGINE RESOLUTION:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JAVA TEST CODE: given().contentType(ContentType.JSON).body(studentPojo).when().post(...) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OBJECT MAPPER DISCOVERY ENGINE (io.restassured.internal.mapping.ObjectMapping) β
β βββ 1. Check explicit ObjectMapper in request: .body(studentPojo, ObjectMapperType.JACKSON_2)β
β βββ 2. Inspect Classpath for Jackson 2.x (com.fasterxml.jackson.databind.ObjectMapper) β
β βββ 3. Inspect Classpath for Jackson 1.x (org.codehaus.jackson.map.ObjectMapper) β
β βββ 4. Inspect Classpath for Google Gson (com.google.gson.Gson) β
β βββ 5. Inspect Classpath for Apache Johnzon / Yasson (Jakarta JSON-B) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Selected: Jackson 2.x Databind)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JACKSON SERIALIZATION PIPELINE β
β βββ 1. Introspect POJO: Evaluates fields, getters, accessors, and inheritance trees β
β βββ 2. Apply Jackson Annotations: β
β β β’ @JsonProperty("wire_key") βββΊ Rename Java camelCase to API snake_case β
β β β’ @JsonInclude(Include.NON_NULL) βββΊ Omit null fields from outbound payload β
β β β’ @JsonFormat(pattern = "...") βββΊ Format java.time.LocalDate into ISO strings β
β βββ 3. Convert to Stream: Invokes ObjectMapper.writeValueAsBytes(studentPojo) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP WIRE TRANSMISSION: Content-Type: application/json; charset=UTF-8 β
β Payload: {"student_id":"STU-88219","full_name":"Nikita Sharma","enrolled_credits":16} β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
package com.nikita.restassured.models;
import java.io.Serializable;
import java.util.Objects;
public class StudentRegistrationRequest implements Serializable {
private static final long serialVersionUID = 1L;
private String fullName;
private String email;
private String academicTrack;
private int enrolledCredits;
private boolean active;
// 1. Mandatory Default No-Argument Constructor (Required by Jackson for reflective instantiation)
public StudentRegistrationRequest() {
}
// 2. Parameterized Constructor for clean instantiation in test methods
public StudentRegistrationRequest(String fullName, String email, String academicTrack,
int enrolledCredits, boolean active) {
this.fullName = fullName;
this.email = email;
this.academicTrack = academicTrack;
this.enrolledCredits = enrolledCredits;
this.active = active;
}
// 3. Standard Getters and Setters
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getAcademicTrack() { return academicTrack; }
public void setAcademicTrack(String academicTrack) { this.academicTrack = academicTrack; }
public int getEnrolledCredits() { return enrolledCredits; }
public void setEnrolledCredits(int enrolledCredits) { this.enrolledCredits = enrolledCredits; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
@Override
public String toString() {
return "StudentRegistrationRequest{" +
"fullName='" + fullName + '\'' +
", email='" + email + '\'' +
", academicTrack='" + academicTrack + '\'' +
", enrolledCredits=" + enrolledCredits +
", active=" + active +
'}';
}
}
.body(pojo). REST Assured marshals the object into JSON, dispatches the HTTP request, and asserts that the server persisted the fields accurately.
package com.nikita.restassured.serialization;
import com.nikita.restassured.models.StudentRegistrationRequest;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class PojoSerializationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Serialize Java POJO into JSON body for POST request")
public void testSerializePojoInPostRequest() {
// Step 1: Instantiate Java POJO with test data
StudentRegistrationRequest newStudent = new StudentRegistrationRequest(
"Nikita Sharma",
"nikita.sharma@nikita-infotech.com",
"ENTERPRISE_AUTOMATION",
16,
true
);
// Step 2: Pass POJO directly into .body(); Jackson handles marshaling automatically
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.body(newStudent)
.log().body() // Prints serialized JSON wire payload to console
.when()
.post("/students")
.then()
.statusCode(201)
.body("status", equalTo("SUCCESS"))
.body("data.id", startsWith("STU-"))
.body("data.fullName", equalTo("Nikita Sharma"))
.body("data.enrolledCredits", equalTo(16))
.body("data.active", equalTo(true));
System.out.println("[β] Java POJO serialized to JSON and accepted by server.");
}
}
@JsonProperty annotation to map Java camelCase attributes to API snake_case wire fields.
package com.nikita.restassured.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
// Optional: Enforce explicit serialization order on the wire
@JsonPropertyOrder({"student_code", "full_legal_name", "primary_email", "credits_count"})
public class AnnotatedStudentPayload {
// Maps Java field 'studentCode' to wire JSON key 'student_code'
@JsonProperty("student_code")
private String studentCode;
// Maps Java field 'fullLegalName' to wire JSON key 'full_legal_name'
@JsonProperty("full_legal_name")
private String fullLegalName;
@JsonProperty("primary_email")
private String primaryEmail;
@JsonProperty("credits_count")
private int creditsCount;
public AnnotatedStudentPayload() {
}
public AnnotatedStudentPayload(String studentCode, String fullLegalName,
String primaryEmail, int creditsCount) {
this.studentCode = studentCode;
this.fullLegalName = fullLegalName;
this.primaryEmail = primaryEmail;
this.creditsCount = creditsCount;
}
public String getStudentCode() { return studentCode; }
public void setStudentCode(String studentCode) { this.studentCode = studentCode; }
public String getFullLegalName() { return fullLegalName; }
public void setFullLegalName(String fullLegalName) { this.fullLegalName = fullLegalName; }
public String getPrimaryEmail() { return primaryEmail; }
public void setPrimaryEmail(String primaryEmail) { this.primaryEmail = primaryEmail; }
public int getCreditsCount() { return creditsCount; }
public void setCreditsCount(int creditsCount) { this.creditsCount = creditsCount; }
}
@JsonInclude(JsonInclude.Include.NON_NULL) to omit null values, keeping partial update payloads clean.
package com.nikita.restassured.models;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
// Instructs Jackson to omit fields whose value is null during serialization
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PartialStudentPatchRequest {
@JsonProperty("full_name")
private String fullName;
@JsonProperty("academic_track")
private String academicTrack;
@JsonProperty("notes")
private String optionalNotes;
// Default constructor
public PartialStudentPatchRequest() {
}
// Constructor providing only track (fullName and optionalNotes remain null)
public PartialStudentPatchRequest(String academicTrack) {
this.academicTrack = academicTrack;
this.fullName = null;
this.optionalNotes = null;
}
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getAcademicTrack() { return academicTrack; }
public void setAcademicTrack(String academicTrack) { this.academicTrack = academicTrack; }
public String getOptionalNotes() { return optionalNotes; }
public void setOptionalNotes(String optionalNotes) { this.optionalNotes = optionalNotes; }
}
@JsonIgnore on transient fields and @JsonIgnoreProperties(ignoreUnknown = true) for resilient bidirectional data transfer.
package com.nikita.restassured.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
// ignoreUnknown = true ensures extra incoming fields during deserialization do not throw UnrecognizedPropertyException
@JsonIgnoreProperties(ignoreUnknown = true)
public class StudentEntityModel {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
// @JsonIgnore prevents internal framework metadata from being serialized into the request body
@JsonIgnore
private String internalTestExecutionId;
@JsonIgnore
private boolean isRetriedRun;
public StudentEntityModel() {
}
public StudentEntityModel(String id, String name, String internalTestExecutionId) {
this.id = id;
this.name = name;
this.internalTestExecutionId = internalTestExecutionId;
this.isRetriedRun = false;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getInternalTestExecutionId() { return internalTestExecutionId; }
public void setInternalTestExecutionId(String internalTestExecutionId) {
this.internalTestExecutionId = internalTestExecutionId;
}
public boolean isRetriedRun() { return isRetriedRun; }
public void setRetriedRun(boolean retriedRun) { isRetriedRun = retriedRun; }
}
ObjectMapperType.JACKSON_2 or ObjectMapperType.GSON directly inside .body() to avoid ambiguity.
package com.nikita.restassured.serialization;
import com.nikita.restassured.models.StudentRegistrationRequest;
import io.restassured.http.ContentType;
import io.restassured.mapper.ObjectMapperType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class ExplicitObjectMapperTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Force Jackson 2.x Databind mapper explicitly")
public void testExplicitJacksonMapper() {
StudentRegistrationRequest payload = new StudentRegistrationRequest(
"Aarav Deshmukh",
"aarav.deshmukh@nikita-infotech.com",
"FULLSTACK_SDET",
12,
true
);
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
// Explicitly dictate Jackson 2.x as the target serialization mapper:
.body(payload, ObjectMapperType.JACKSON_2)
.when()
.post("/students")
.then()
.statusCode(201)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Serialized explicitly via ObjectMapperType.JACKSON_2.");
}
@Test(description = "Force Google Gson mapper explicitly")
public void testExplicitGsonMapper() {
StudentRegistrationRequest payload = new StudentRegistrationRequest(
"Rohan Verma",
"rohan.verma@nikita-infotech.com",
"CLOUD_DEVOPS_QA",
8,
true
);
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
// Explicitly dictate Google Gson as the target serialization mapper:
.body(payload, ObjectMapperType.GSON)
.when()
.post("/students")
.then()
.statusCode(201)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Serialized explicitly via ObjectMapperType.GSON.");
}
}
LocalDate, Instant). Registers JavaTimeModule and uses @JsonFormat to format date properties into standard ISO-8601 strings.
package com.nikita.restassured.models;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
import java.time.OffsetDateTime;
public class StudentEnrollmentSchedule {
@JsonProperty("student_id")
private String studentId;
// Formats LocalDate as an ISO calendar date: "yyyy-MM-dd"
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonProperty("commencement_date")
private LocalDate commencementDate;
// Formats OffsetDateTime into full ISO-8601 timestamp with zone offset
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")
@JsonProperty("orientation_timestamp")
private OffsetDateTime orientationTimestamp;
public StudentEnrollmentSchedule() {
}
public StudentEnrollmentSchedule(String studentId, LocalDate commencementDate,
OffsetDateTime orientationTimestamp) {
this.studentId = studentId;
this.commencementDate = commencementDate;
this.orientationTimestamp = orientationTimestamp;
}
public String getStudentId() { return studentId; }
public void setStudentId(String studentId) { this.studentId = studentId; }
public LocalDate getCommencementDate() { return commencementDate; }
public void setCommencementDate(LocalDate commencementDate) {
this.commencementDate = commencementDate;
}
public OffsetDateTime getOrientationTimestamp() { return orientationTimestamp; }
public void setOrientationTimestamp(OffsetDateTime orientationTimestamp) {
this.orientationTimestamp = orientationTimestamp;
}
}
InvalidDefinitionException: No serializer found for class (empty beans), fixing missing getters, and configuring FAIL_ON_EMPTY_BEANS.
package com.nikita.restassured.serialization;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.restassured.RestAssured;
import io.restassured.config.ObjectMapperConfig;
import io.restassured.config.RestAssuredConfig;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SerializationTriageTest {
// ==========================================================================
// COMMON ERROR: com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
// No serializer found for class and no properties discovered to create BeanSerializer
// (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
//
// CAUSE: POJO class fields are private and lack public getter methods!
// Jackson inspects getters to discover serializable properties by default.
// ==========================================================================
@BeforeClass
public void configureTolerantJacksonMapper() {
ObjectMapper customMapper = new ObjectMapper();
// Disable failure when a POJO contains no discoverable properties:
customMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// Apply customized ObjectMapper globally across REST Assured
RestAssured.config = RestAssuredConfig.config().objectMapperConfig(
ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory(
(type, charset) -> customMapper
)
);
System.out.println("[*] Configured custom Jackson mapper with FAIL_ON_EMPTY_BEANS disabled.");
}
// Example POJO with private fields but missing getters (Fix: add getters or @JsonProperty)
static class BrokenEmptyBean {
private String message = "Test Message";
// FIX: Add public getter so Jackson can discover the property:
public String getMessage() {
return message;
}
}
@Test(description = "Verify POJO with public getter serializes without InvalidDefinitionException")
public void testSerializeValidBean() {
BrokenEmptyBean bean = new BrokenEmptyBean();
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.contentType("application/json")
.body(bean)
.log().body()
.when()
.post("/echo")
.then()
.statusCode(200);
System.out.println("[β] Serialized bean successfully after ensuring getter visibility.");
}
}
JACKSON SERIALIZATION SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β ANNOTATION / SETTING β TARGET LEVEL β ARGUMENT / VALUE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β @JsonProperty("name") β Field / Getter / Setter β String key name β Renames Java field on wire β
β @JsonInclude β Class / Field β Include.NON_NULL β Excludes null fields from bodyβ
β @JsonIgnore β Field / Getter β Boolean flag β Omits field from serializationβ
β @JsonIgnoreProperties β Class Level β ignoreUnknown=truePrevents failures on extra key β
β @JsonPropertyOrder β Class Level β {"k1", "k2", ..} β Dictates wire property order β
β @JsonFormat β Date / Time Fields β pattern="yyyy-MM"β Formats dates into ISO stringsβ
β ObjectMapperType β Request body() parameter β JACKSON_2 / GSON β Forces explicit mapper engine β
β FAIL_ON_EMPTY_BEANS β Jackson SerializationFeature β Boolean flag β Prevents error on zero gettersβ
β JavaTimeModule β ObjectMapper.registerModule()β Module instance β Adds Java 8 java.time support β
β Default No-Arg ConstructorClass Level β public ClassName()Mandatory for Jackson models β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 POJO SERIALIZATION BEST PRACTICES: β
β 1. Always provide a default no-arg constructor: Required by Jackson to instantiate objects. β
β 2. Use @JsonProperty for API contract alignment: Keep Java code camelCase while wire JSON is snake_case. β
β 3. Apply @JsonInclude(Include.NON_NULL): Keep PATCH request bodies clean by omitting unassigned nulls. β
β 4. Register JavaTimeModule for date fields: Avoid serialization failures on LocalDate and Instant. β
β 5. Use ObjectMapperType to avoid ambiguity: Pin JACKSON_2 if multiple mappers exist on the classpath. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ