0
# Object Mapping
1
2
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.
3
4
## Capabilities
5
6
### Request Body Object Mapping
7
8
Automatic serialization of Java objects to JSON/XML for request bodies.
9
10
```java { .api }
11
// From RequestSpecification interface
12
interface RequestSpecification {
13
/**
14
* Set request body from Java object (automatically serialized)
15
* @param object The object to serialize as request body
16
* @return Updated request specification
17
*/
18
RequestSpecification body(Object object);
19
20
/**
21
* Set request body from object with specific object mapper
22
* @param object The object to serialize
23
* @param mapper Custom object mapper to use for serialization
24
* @return Updated request specification
25
*/
26
RequestSpecification body(Object object, ObjectMapper mapper);
27
28
/**
29
* Set request body from object with specific object mapper type
30
* @param object The object to serialize
31
* @param mapperType Type of object mapper to use (Jackson, Gson, JAXB)
32
* @return Updated request specification
33
*/
34
RequestSpecification body(Object object, ObjectMapperType mapperType);
35
}
36
```
37
38
**Usage Examples:**
39
40
```java
41
// Basic object serialization (uses default mapper)
42
User user = new User("John", "john@example.com", 25);
43
given()
44
.contentType(ContentType.JSON)
45
.body(user)
46
.when()
47
.post("/users")
48
.then()
49
.statusCode(201);
50
51
// Using specific mapper type
52
Product product = new Product("Laptop", 999.99);
53
given()
54
.contentType(ContentType.JSON)
55
.body(product, ObjectMapperType.GSON)
56
.when()
57
.post("/products");
58
59
// Using custom object mapper
60
ObjectMapper customMapper = new MyCustomObjectMapper();
61
given()
62
.contentType(ContentType.JSON)
63
.body(user, customMapper)
64
.when()
65
.post("/users");
66
```
67
68
### Response Body Object Mapping
69
70
Automatic deserialization of JSON/XML response bodies to Java objects.
71
72
```java { .api }
73
// From ResponseBody interface
74
interface ResponseBody<T> {
75
/**
76
* Deserialize response body to specified class
77
* @param cls Class to deserialize response to
78
* @return Deserialized object
79
*/
80
<T> T as(Class<T> cls);
81
82
/**
83
* Deserialize response body to specified class with custom mapper
84
* @param cls Class to deserialize response to
85
* @param mapper Custom object mapper to use
86
* @return Deserialized object
87
*/
88
<T> T as(Class<T> cls, ObjectMapper mapper);
89
90
/**
91
* Deserialize response body to specified class with mapper type
92
* @param cls Class to deserialize response to
93
* @param mapperType Type of object mapper to use
94
* @return Deserialized object
95
*/
96
<T> T as(Class<T> cls, ObjectMapperType mapperType);
97
98
/**
99
* Deserialize response body using TypeRef for generic types
100
* @param typeRef TypeRef containing generic type information
101
* @return Deserialized object with preserved generic types
102
*/
103
<T> T as(TypeRef<T> typeRef);
104
105
/**
106
* Deserialize response body using TypeRef with custom mapper
107
* @param typeRef TypeRef containing generic type information
108
* @param mapper Custom object mapper to use
109
* @return Deserialized object with preserved generic types
110
*/
111
<T> T as(TypeRef<T> typeRef, ObjectMapper mapper);
112
113
/**
114
* Deserialize response body using TypeRef with mapper type
115
* @param typeRef TypeRef containing generic type information
116
* @param mapperType Type of object mapper to use
117
* @return Deserialized object with preserved generic types
118
*/
119
<T> T as(TypeRef<T> typeRef, ObjectMapperType mapperType);
120
}
121
122
// From ExtractableResponse interface
123
interface ExtractableResponse<T> {
124
/**
125
* Extract and deserialize response body to specified class
126
* @param cls Class to deserialize response to
127
* @return Deserialized object
128
*/
129
<T> T as(Class<T> cls);
130
131
/**
132
* Extract and deserialize response body with custom mapper
133
* @param cls Class to deserialize response to
134
* @param mapper Custom object mapper to use
135
* @return Deserialized object
136
*/
137
<T> T as(Class<T> cls, ObjectMapper mapper);
138
139
/**
140
* Extract and deserialize response body with mapper type
141
* @param cls Class to deserialize response to
142
* @param mapperType Type of object mapper to use
143
* @return Deserialized object
144
*/
145
<T> T as(Class<T> cls, ObjectMapperType mapperType);
146
}
147
```
148
149
**Usage Examples:**
150
151
```java
152
// Basic object deserialization
153
User user = get("/users/1").as(User.class);
154
155
// Using specific mapper type
156
User user = get("/users/1").as(User.class, ObjectMapperType.JACKSON_2);
157
158
// Generic type deserialization using TypeRef
159
List<User> users = get("/users").as(new TypeRef<List<User>>() {});
160
161
// Map deserialization
162
Map<String, Object> userMap = get("/users/1").as(new TypeRef<Map<String, Object>>() {});
163
164
// Complex nested generics
165
Response<List<User>> response = get("/users")
166
.as(new TypeRef<Response<List<User>>>() {});
167
168
// With validation chain
169
User user = given()
170
.queryParam("include", "profile")
171
.when()
172
.get("/users/1")
173
.then()
174
.statusCode(200)
175
.contentType(ContentType.JSON)
176
.extract()
177
.as(User.class);
178
```
179
180
### Object Mapper Types
181
182
Predefined object mapper types supported by REST Assured.
183
184
```java { .api }
185
/**
186
* Enumeration of supported object mapper types
187
*/
188
enum ObjectMapperType {
189
/**
190
* Jackson 1.x object mapper (org.codehaus.jackson)
191
*/
192
JACKSON_1,
193
194
/**
195
* Jackson 2.x object mapper (com.fasterxml.jackson)
196
*/
197
JACKSON_2,
198
199
/**
200
* Google Gson object mapper
201
*/
202
GSON,
203
204
/**
205
* JAXB object mapper for XML binding
206
*/
207
JAXB
208
}
209
```
210
211
### Custom Object Mapper Interface
212
213
Interface for implementing custom serialization/deserialization logic.
214
215
```java { .api }
216
/**
217
* Interface for custom object mappers
218
*/
219
interface ObjectMapper {
220
/**
221
* Serialize an object to string representation
222
* @param context Serialization context containing object and configuration
223
* @return Serialized string representation
224
*/
225
Object serialize(ObjectMapperSerializationContext context);
226
227
/**
228
* Deserialize string representation to object
229
* @param context Deserialization context containing data and target type
230
* @return Deserialized object
231
*/
232
<T> T deserialize(ObjectMapperDeserializationContext context);
233
}
234
235
/**
236
* Context for object serialization
237
*/
238
interface ObjectMapperSerializationContext {
239
/**
240
* Get the object to serialize
241
* @return Object to be serialized
242
*/
243
Object getObjectToSerialize();
244
245
/**
246
* Get the content type for serialization
247
* @return Content type string
248
*/
249
String getContentType();
250
251
/**
252
* Get the charset for serialization
253
* @return Charset string
254
*/
255
String getCharset();
256
}
257
258
/**
259
* Context for object deserialization
260
*/
261
interface ObjectMapperDeserializationContext {
262
/**
263
* Get the data to deserialize
264
* @return Data string to deserialize
265
*/
266
String getDataToDeserialize();
267
268
/**
269
* Get the target type for deserialization
270
* @return Class to deserialize to
271
*/
272
Class<?> getType();
273
274
/**
275
* Get the content type of the data
276
* @return Content type string
277
*/
278
String getContentType();
279
280
/**
281
* Get the charset of the data
282
* @return Charset string
283
*/
284
String getCharset();
285
}
286
```
287
288
**Usage Examples:**
289
290
```java
291
// Custom object mapper implementation
292
public class CustomObjectMapper implements ObjectMapper {
293
@Override
294
public Object serialize(ObjectMapperSerializationContext context) {
295
Object obj = context.getObjectToSerialize();
296
// Custom serialization logic
297
return customSerialize(obj);
298
}
299
300
@Override
301
public <T> T deserialize(ObjectMapperDeserializationContext context) {
302
String data = context.getDataToDeserialize();
303
Class<T> type = (Class<T>) context.getType();
304
// Custom deserialization logic
305
return customDeserialize(data, type);
306
}
307
}
308
309
// Using custom object mapper
310
ObjectMapper customMapper = new CustomObjectMapper();
311
User user = get("/users/1").as(User.class, customMapper);
312
```
313
314
### Object Mapper Configuration
315
316
Configuration options for object mapping behavior.
317
318
```java { .api }
319
/**
320
* Configuration for object mapping behavior
321
*/
322
class ObjectMapperConfig {
323
/**
324
* Create default object mapper configuration
325
* @return Default configuration
326
*/
327
static ObjectMapperConfig objectMapperConfig();
328
329
/**
330
* Set default object mapper type for all operations
331
* @param defaultObjectMapperType The default mapper type
332
* @return Updated configuration
333
*/
334
ObjectMapperConfig defaultObjectMapperType(ObjectMapperType defaultObjectMapperType);
335
336
/**
337
* Set custom default object mapper
338
* @param objectMapper Custom object mapper instance
339
* @return Updated configuration
340
*/
341
ObjectMapperConfig defaultObjectMapper(ObjectMapper objectMapper);
342
343
/**
344
* Configure Jackson 1.x object mapper instance
345
* @param objectMapper Jackson 1.x ObjectMapper
346
* @return Updated configuration
347
*/
348
ObjectMapperConfig jackson1ObjectMapper(org.codehaus.jackson.map.ObjectMapper objectMapper);
349
350
/**
351
* Configure Jackson 2.x object mapper instance
352
* @param objectMapper Jackson 2.x ObjectMapper
353
* @return Updated configuration
354
*/
355
ObjectMapperConfig jackson2ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper objectMapper);
356
357
/**
358
* Configure Gson instance
359
* @param gson Gson instance
360
* @return Updated configuration
361
*/
362
ObjectMapperConfig gsonObjectMapper(Gson gson);
363
364
/**
365
* Configure JAXB context path
366
* @param contextPath JAXB context path for XML mapping
367
* @return Updated configuration
368
*/
369
ObjectMapperConfig jaxbObjectMapper(String contextPath);
370
371
/**
372
* Configure JAXB context
373
* @param context JAXB context for XML mapping
374
* @return Updated configuration
375
*/
376
ObjectMapperConfig jaxbObjectMapper(JAXBContext context);
377
}
378
```
379
380
**Usage Examples:**
381
382
```java
383
// Configure default object mapper type globally
384
RestAssured.config = RestAssured.config()
385
.objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
386
.defaultObjectMapperType(ObjectMapperType.GSON));
387
388
// Configure custom Jackson settings
389
ObjectMapper jacksonMapper = new ObjectMapper();
390
jacksonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
391
jacksonMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
392
393
RestAssured.config = RestAssured.config()
394
.objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
395
.jackson2ObjectMapper(jacksonMapper));
396
397
// Configure Gson with custom settings
398
Gson gson = new GsonBuilder()
399
.setDateFormat("yyyy-MM-dd HH:mm:ss")
400
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
401
.create();
402
403
RestAssured.config = RestAssured.config()
404
.objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
405
.gsonObjectMapper(gson));
406
```
407
408
### TypeRef for Generic Types
409
410
Type reference utility for preserving generic type information during deserialization.
411
412
```java { .api }
413
/**
414
* Type reference for preserving generic type information
415
*/
416
abstract class TypeRef<T> {
417
/**
418
* Create a new TypeRef. Typically used as anonymous inner class:
419
* new TypeRef<List<User>>() {}
420
*/
421
protected TypeRef();
422
423
/**
424
* Get the referenced type
425
* @return The Type object representing the generic type
426
*/
427
Type getType();
428
}
429
```
430
431
**Usage Examples:**
432
433
```java
434
// List of objects
435
List<User> users = get("/users").as(new TypeRef<List<User>>() {});
436
437
// Map with specific value type
438
Map<String, User> userMap = get("/users/by-name").as(new TypeRef<Map<String, User>>() {});
439
440
// Complex nested generics
441
ApiResponse<List<User>> response = get("/api/users")
442
.as(new TypeRef<ApiResponse<List<User>>>() {});
443
444
// Array types
445
User[] userArray = get("/users").as(new TypeRef<User[]>() {});
446
447
// Generic wrapper classes
448
PagedResult<User> pagedUsers = get("/users")
449
.queryParam("page", 1)
450
.as(new TypeRef<PagedResult<User>>() {});
451
```
452
453
### JSON and XML Configuration
454
455
Specific configuration for JSON and XML processing.
456
457
```java { .api }
458
/**
459
* JSON processing configuration
460
*/
461
class JsonConfig {
462
static JsonConfig jsonConfig();
463
464
/**
465
* Configure number return type for JSONPath
466
* @param numberReturnType How numbers should be returned
467
* @return Updated JSON configuration
468
*/
469
JsonConfig numberReturnType(JsonPathConfig.NumberReturnType numberReturnType);
470
471
/**
472
* Configure JSONPath configuration
473
* @param jsonPathConfig JSONPath configuration
474
* @return Updated JSON configuration
475
*/
476
JsonConfig jsonPathConfig(JsonPathConfig jsonPathConfig);
477
}
478
479
/**
480
* XML processing configuration
481
*/
482
class XmlConfig {
483
static XmlConfig xmlConfig();
484
485
/**
486
* Configure XML namespace awareness
487
* @param isNamespaceAware Whether to be namespace aware
488
* @return Updated XML configuration
489
*/
490
XmlConfig namespaceAware(boolean isNamespaceAware);
491
492
/**
493
* Configure XML validation
494
* @param shouldValidate Whether to validate XML
495
* @return Updated XML configuration
496
*/
497
XmlConfig validate(boolean shouldValidate);
498
499
/**
500
* Configure XPath configuration
501
* @param xmlPathConfig XPath configuration
502
* @return Updated XML configuration
503
*/
504
XmlConfig xmlPathConfig(XmlPathConfig xmlPathConfig);
505
}
506
```
507
508
## Types
509
510
```java { .api }
511
// Main object mapper interface
512
interface ObjectMapper {
513
Object serialize(ObjectMapperSerializationContext context);
514
<T> T deserialize(ObjectMapperDeserializationContext context);
515
}
516
517
// Object mapper types enumeration
518
enum ObjectMapperType {
519
JACKSON_1, JACKSON_2, GSON, JAXB
520
}
521
522
// Type reference for generic types
523
abstract class TypeRef<T> {
524
protected TypeRef();
525
Type getType();
526
}
527
528
// Configuration classes
529
class ObjectMapperConfig {
530
// All configuration methods listed above
531
}
532
533
class JsonConfig {
534
// JSON-specific configuration methods
535
}
536
537
class XmlConfig {
538
// XML-specific configuration methods
539
}
540
541
// Context interfaces for custom mappers
542
interface ObjectMapperSerializationContext {
543
Object getObjectToSerialize();
544
String getContentType();
545
String getCharset();
546
}
547
548
interface ObjectMapperDeserializationContext {
549
String getDataToDeserialize();
550
Class<?> getType();
551
String getContentType();
552
String getCharset();
553
}
554
```
555
556
**Complete Example:**
557
558
```java
559
// User domain object
560
public class User {
561
private String name;
562
private String email;
563
private int age;
564
private List<String> roles;
565
566
// constructors, getters, setters
567
}
568
569
// API response wrapper
570
public class ApiResponse<T> {
571
private T data;
572
private String status;
573
private String message;
574
575
// constructors, getters, setters
576
}
577
578
// Complete object mapping example
579
public void testUserAPI() {
580
// Configure object mapping
581
RestAssured.config = RestAssured.config()
582
.objectMapperConfig(ObjectMapperConfig.objectMapperConfig()
583
.defaultObjectMapperType(ObjectMapperType.JACKSON_2));
584
585
// Create user
586
User newUser = new User("John", "john@example.com", 25, Arrays.asList("USER", "ADMIN"));
587
588
User createdUser = given()
589
.contentType(ContentType.JSON)
590
.body(newUser)
591
.when()
592
.post("/users")
593
.then()
594
.statusCode(201)
595
.extract()
596
.as(User.class);
597
598
// Get users list
599
List<User> users = get("/users").as(new TypeRef<List<User>>() {});
600
601
// Get API response wrapper
602
ApiResponse<User> response = get("/users/" + createdUser.getId())
603
.as(new TypeRef<ApiResponse<User>>() {});
604
605
User user = response.getData();
606
assertEquals("John", user.getName());
607
}
608
```