CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-rest-assured--rest-assured

Java DSL for easy testing of REST services

Pending
Overview
Eval results
Files

object-mapping.mddocs/

Object Mapping

Automatic serialization and deserialization of Java objects to/from JSON and XML using Jackson, Gson, JAXB, or custom object mappers for seamless REST API testing.

Capabilities

Request Body Object Mapping

Automatic serialization of Java objects to JSON/XML for request bodies.

// From RequestSpecification interface
interface RequestSpecification {
    /**
     * Set request body from Java object (automatically serialized)
     * @param object The object to serialize as request body
     * @return Updated request specification
     */
    RequestSpecification body(Object object);
    
    /**
     * Set request body from object with specific object mapper
     * @param object The object to serialize
     * @param mapper Custom object mapper to use for serialization
     * @return Updated request specification
     */
    RequestSpecification body(Object object, ObjectMapper mapper);
    
    /**
     * Set request body from object with specific object mapper type
     * @param object The object to serialize
     * @param mapperType Type of object mapper to use (Jackson, Gson, JAXB)
     * @return Updated request specification
     */
    RequestSpecification body(Object object, ObjectMapperType mapperType);
}

Usage Examples:

// Basic object serialization (uses default mapper)
User user = new User("John", "john@example.com", 25);
given()
    .contentType(ContentType.JSON)
    .body(user)
.when()
    .post("/users")
.then()
    .statusCode(201);

// Using specific mapper type
Product product = new Product("Laptop", 999.99);
given()
    .contentType(ContentType.JSON)
    .body(product, ObjectMapperType.GSON)
.when()
    .post("/products");

// Using custom object mapper
ObjectMapper customMapper = new MyCustomObjectMapper();
given()
    .contentType(ContentType.JSON)
    .body(user, customMapper)
.when()
    .post("/users");

Response Body Object Mapping

Automatic deserialization of JSON/XML response bodies to Java objects.

// From ResponseBody interface
interface ResponseBody<T> {
    /**
     * Deserialize response body to specified class
     * @param cls Class to deserialize response to
     * @return Deserialized object
     */
    <T> T as(Class<T> cls);
    
    /**
     * Deserialize response body to specified class with custom mapper
     * @param cls Class to deserialize response to
     * @param mapper Custom object mapper to use
     * @return Deserialized object
     */
    <T> T as(Class<T> cls, ObjectMapper mapper);
    
    /**
     * Deserialize response body to specified class with mapper type
     * @param cls Class to deserialize response to
     * @param mapperType Type of object mapper to use
     * @return Deserialized object
     */
    <T> T as(Class<T> cls, ObjectMapperType mapperType);
    
    /**
     * Deserialize response body using TypeRef for generic types
     * @param typeRef TypeRef containing generic type information
     * @return Deserialized object with preserved generic types
     */
    <T> T as(TypeRef<T> typeRef);
    
    /**
     * Deserialize response body using TypeRef with custom mapper
     * @param typeRef TypeRef containing generic type information
     * @param mapper Custom object mapper to use
     * @return Deserialized object with preserved generic types
     */
    <T> T as(TypeRef<T> typeRef, ObjectMapper mapper);
    
    /**
     * Deserialize response body using TypeRef with mapper type
     * @param typeRef TypeRef containing generic type information
     * @param mapperType Type of object mapper to use
     * @return Deserialized object with preserved generic types
     */
    <T> T as(TypeRef<T> typeRef, ObjectMapperType mapperType);
}

// From ExtractableResponse interface  
interface ExtractableResponse<T> {
    /**
     * Extract and deserialize response body to specified class
     * @param cls Class to deserialize response to
     * @return Deserialized object
     */
    <T> T as(Class<T> cls);
    
    /**
     * Extract and deserialize response body with custom mapper
     * @param cls Class to deserialize response to
     * @param mapper Custom object mapper to use
     * @return Deserialized object
     */
    <T> T as(Class<T> cls, ObjectMapper mapper);
    
    /**
     * Extract and deserialize response body with mapper type
     * @param cls Class to deserialize response to
     * @param mapperType Type of object mapper to use
     * @return Deserialized object
     */
    <T> T as(Class<T> cls, ObjectMapperType mapperType);
}

Usage Examples:

// Basic object deserialization
User user = get("/users/1").as(User.class);

// Using specific mapper type
User user = get("/users/1").as(User.class, ObjectMapperType.JACKSON_2);

// Generic type deserialization using TypeRef
List<User> users = get("/users").as(new TypeRef<List<User>>() {});

// Map deserialization
Map<String, Object> userMap = get("/users/1").as(new TypeRef<Map<String, Object>>() {});

// Complex nested generics
Response<List<User>> response = get("/users")
    .as(new TypeRef<Response<List<User>>>() {});

// With validation chain
User user = given()
    .queryParam("include", "profile")
.when()
    .get("/users/1")
.then()
    .statusCode(200)
    .contentType(ContentType.JSON)
    .extract()
    .as(User.class);

Object Mapper Types

Predefined object mapper types supported by REST Assured.

/**
 * Enumeration of supported object mapper types
 */
enum ObjectMapperType {
    /**
     * Jackson 1.x object mapper (org.codehaus.jackson)
     */
    JACKSON_1,
    
    /**
     * Jackson 2.x object mapper (com.fasterxml.jackson)
     */
    JACKSON_2,
    
    /**
     * Google Gson object mapper
     */
    GSON,
    
    /**
     * JAXB object mapper for XML binding
     */
    JAXB
}

Custom Object Mapper Interface

Interface for implementing custom serialization/deserialization logic.

/**
 * Interface for custom object mappers
 */
interface ObjectMapper {
    /**
     * Serialize an object to string representation
     * @param context Serialization context containing object and configuration
     * @return Serialized string representation
     */
    Object serialize(ObjectMapperSerializationContext context);
    
    /**
     * Deserialize string representation to object
     * @param context Deserialization context containing data and target type
     * @return Deserialized object
     */
    <T> T deserialize(ObjectMapperDeserializationContext context);
}

/**
 * Context for object serialization
 */
interface ObjectMapperSerializationContext {
    /**
     * Get the object to serialize
     * @return Object to be serialized
     */
    Object getObjectToSerialize();
    
    /**
     * Get the content type for serialization
     * @return Content type string
     */
    String getContentType();
    
    /**
     * Get the charset for serialization
     * @return Charset string
     */
    String getCharset();
}

/**
 * Context for object deserialization
 */
interface ObjectMapperDeserializationContext {
    /**
     * Get the data to deserialize
     * @return Data string to deserialize
     */
    String getDataToDeserialize();
    
    /**
     * Get the target type for deserialization
     * @return Class to deserialize to
     */
    Class<?> getType();
    
    /**
     * Get the content type of the data
     * @return Content type string
     */
    String getContentType();
    
    /**
     * Get the charset of the data
     * @return Charset string
     */
    String getCharset();
}

Usage Examples:

// Custom object mapper implementation
public class CustomObjectMapper implements ObjectMapper {
    @Override
    public Object serialize(ObjectMapperSerializationContext context) {
        Object obj = context.getObjectToSerialize();
        // Custom serialization logic
        return customSerialize(obj);
    }
    
    @Override
    public <T> T deserialize(ObjectMapperDeserializationContext context) {
        String data = context.getDataToDeserialize();
        Class<T> type = (Class<T>) context.getType();
        // Custom deserialization logic
        return customDeserialize(data, type);
    }
}

// Using custom object mapper
ObjectMapper customMapper = new CustomObjectMapper();
User user = get("/users/1").as(User.class, customMapper);

Object Mapper Configuration

Configuration options for object mapping behavior.

/**
 * Configuration for object mapping behavior
 */
class ObjectMapperConfig {
    /**
     * Create default object mapper configuration
     * @return Default configuration
     */
    static ObjectMapperConfig objectMapperConfig();
    
    /**
     * Set default object mapper type for all operations
     * @param defaultObjectMapperType The default mapper type
     * @return Updated configuration
     */
    ObjectMapperConfig defaultObjectMapperType(ObjectMapperType defaultObjectMapperType);
    
    /**
     * Set custom default object mapper
     * @param objectMapper Custom object mapper instance
     * @return Updated configuration
     */
    ObjectMapperConfig defaultObjectMapper(ObjectMapper objectMapper);
    
    /**
     * Configure Jackson 1.x object mapper instance
     * @param objectMapper Jackson 1.x ObjectMapper
     * @return Updated configuration
     */
    ObjectMapperConfig jackson1ObjectMapper(org.codehaus.jackson.map.ObjectMapper objectMapper);
    
    /**
     * Configure Jackson 2.x object mapper instance
     * @param objectMapper Jackson 2.x ObjectMapper
     * @return Updated configuration
     */
    ObjectMapperConfig jackson2ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper objectMapper);
    
    /**
     * Configure Gson instance
     * @param gson Gson instance
     * @return Updated configuration
     */
    ObjectMapperConfig gsonObjectMapper(Gson gson);
    
    /**
     * Configure JAXB context path
     * @param contextPath JAXB context path for XML mapping
     * @return Updated configuration
     */
    ObjectMapperConfig jaxbObjectMapper(String contextPath);
    
    /**
     * Configure JAXB context
     * @param context JAXB context for XML mapping
     * @return Updated configuration
     */
    ObjectMapperConfig jaxbObjectMapper(JAXBContext context);
}

Usage Examples:

// Configure default object mapper type globally
RestAssured.config = RestAssured.config()
    .objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
        .defaultObjectMapperType(ObjectMapperType.GSON));

// Configure custom Jackson settings
ObjectMapper jacksonMapper = new ObjectMapper();
jacksonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jacksonMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

RestAssured.config = RestAssured.config()
    .objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
        .jackson2ObjectMapper(jacksonMapper));

// Configure Gson with custom settings
Gson gson = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd HH:mm:ss")
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create();

RestAssured.config = RestAssured.config()
    .objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
        .gsonObjectMapper(gson));

TypeRef for Generic Types

Type reference utility for preserving generic type information during deserialization.

/**
 * Type reference for preserving generic type information
 */
abstract class TypeRef<T> {
    /**
     * Create a new TypeRef. Typically used as anonymous inner class:
     * new TypeRef<List<User>>() {}
     */
    protected TypeRef();
    
    /**
     * Get the referenced type
     * @return The Type object representing the generic type
     */
    Type getType();
}

Usage Examples:

// List of objects
List<User> users = get("/users").as(new TypeRef<List<User>>() {});

// Map with specific value type
Map<String, User> userMap = get("/users/by-name").as(new TypeRef<Map<String, User>>() {});

// Complex nested generics
ApiResponse<List<User>> response = get("/api/users")
    .as(new TypeRef<ApiResponse<List<User>>>() {});

// Array types
User[] userArray = get("/users").as(new TypeRef<User[]>() {});

// Generic wrapper classes
PagedResult<User> pagedUsers = get("/users")
    .queryParam("page", 1)
    .as(new TypeRef<PagedResult<User>>() {});

JSON and XML Configuration

Specific configuration for JSON and XML processing.

/**
 * JSON processing configuration
 */
class JsonConfig {
    static JsonConfig jsonConfig();
    
    /**
     * Configure number return type for JSONPath
     * @param numberReturnType How numbers should be returned
     * @return Updated JSON configuration
     */
    JsonConfig numberReturnType(JsonPathConfig.NumberReturnType numberReturnType);
    
    /**
     * Configure JSONPath configuration
     * @param jsonPathConfig JSONPath configuration
     * @return Updated JSON configuration
     */
    JsonConfig jsonPathConfig(JsonPathConfig jsonPathConfig);
}

/**
 * XML processing configuration
 */
class XmlConfig {
    static XmlConfig xmlConfig();
    
    /**
     * Configure XML namespace awareness
     * @param isNamespaceAware Whether to be namespace aware
     * @return Updated XML configuration
     */
    XmlConfig namespaceAware(boolean isNamespaceAware);
    
    /**
     * Configure XML validation
     * @param shouldValidate Whether to validate XML
     * @return Updated XML configuration
     */
    XmlConfig validate(boolean shouldValidate);
    
    /**
     * Configure XPath configuration
     * @param xmlPathConfig XPath configuration
     * @return Updated XML configuration
     */
    XmlConfig xmlPathConfig(XmlPathConfig xmlPathConfig);
}

Types

// Main object mapper interface
interface ObjectMapper {
    Object serialize(ObjectMapperSerializationContext context);
    <T> T deserialize(ObjectMapperDeserializationContext context);
}

// Object mapper types enumeration
enum ObjectMapperType {
    JACKSON_1, JACKSON_2, GSON, JAXB
}

// Type reference for generic types
abstract class TypeRef<T> {
    protected TypeRef();
    Type getType();
}

// Configuration classes
class ObjectMapperConfig {
    // All configuration methods listed above
}

class JsonConfig {
    // JSON-specific configuration methods
}

class XmlConfig {  
    // XML-specific configuration methods
}

// Context interfaces for custom mappers
interface ObjectMapperSerializationContext {
    Object getObjectToSerialize();
    String getContentType();
    String getCharset();
}

interface ObjectMapperDeserializationContext {
    String getDataToDeserialize();
    Class<?> getType();
    String getContentType();
    String getCharset();
}

Complete Example:

// User domain object
public class User {
    private String name;
    private String email;
    private int age;
    private List<String> roles;
    
    // constructors, getters, setters
}

// API response wrapper
public class ApiResponse<T> {
    private T data;
    private String status;
    private String message;
    
    // constructors, getters, setters
}

// Complete object mapping example
public void testUserAPI() {
    // Configure object mapping
    RestAssured.config = RestAssured.config()
        .objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
            .defaultObjectMapperType(ObjectMapperType.JACKSON_2));
    
    // Create user
    User newUser = new User("John", "john@example.com", 25, Arrays.asList("USER", "ADMIN"));
    
    User createdUser = given()
        .contentType(ContentType.JSON)
        .body(newUser)
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .extract()
        .as(User.class);
    
    // Get users list
    List<User> users = get("/users").as(new TypeRef<List<User>>() {});
    
    // Get API response wrapper
    ApiResponse<User> response = get("/users/" + createdUser.getId())
        .as(new TypeRef<ApiResponse<User>>() {});
    
    User user = response.getData();
    assertEquals("John", user.getName());
}

Install with Tessl CLI

npx tessl i tessl/maven-io-rest-assured--rest-assured

docs

authentication.md

configuration.md

filters-extensions.md

http-operations.md

index.md

object-mapping.md

request-building.md

response-validation.md

tile.json