0
# Serialization
1
2
Jackson's serialization framework provides a flexible and extensible system for converting Java objects to JSON. The framework is built around JsonSerializer implementations, SerializerProvider for context, and various factory and configuration classes that control the serialization process.
3
4
## JsonSerializer
5
6
JsonSerializer is the abstract base class for all serializers that convert Java objects to JSON.
7
8
```java { .api }
9
public abstract class JsonSerializer<T> {
10
// Core serialization method
11
public abstract void serialize(T value, JsonGenerator gen, SerializerProvider serializers) throws IOException;
12
13
// Type-aware serialization (for polymorphic types)
14
public void serializeWithType(T value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException;
15
16
// Metadata methods
17
public Class<T> handledType();
18
public boolean isEmpty(SerializerProvider provider, T value);
19
public boolean isEmpty(T value);
20
public boolean usesObjectId();
21
22
// Contextual serialization
23
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException;
24
25
// Resolution support
26
public void resolve(SerializerProvider provider) throws JsonMappingException;
27
28
// Deprecated delegation
29
public JsonSerializer<T> replaceDelegatee(JsonSerializer<?> delegatee);
30
public JsonSerializer<?> getDelegatee();
31
32
// Schema support
33
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType type) throws JsonMappingException;
34
35
// Iterator support for container types
36
public boolean isUnwrappingSerializer();
37
public JsonSerializer<T> unwrappingSerializer(NameTransformer unwrapper);
38
39
// Null handling marker classes
40
public static abstract class None extends JsonSerializer<Object> { }
41
}
42
```
43
44
## SerializerProvider
45
46
SerializerProvider provides context and factory functionality for serializers during the serialization process.
47
48
```java { .api }
49
public abstract class SerializerProvider extends DatabindContext {
50
// Serializer lookup methods
51
public abstract JsonSerializer<Object> findValueSerializer(Class<?> valueType, BeanProperty property) throws JsonMappingException;
52
public abstract JsonSerializer<Object> findValueSerializer(JavaType valueType, BeanProperty property) throws JsonMappingException;
53
public abstract JsonSerializer<Object> findValueSerializer(Class<?> valueType) throws JsonMappingException;
54
public abstract JsonSerializer<Object> findValueSerializer(JavaType valueType) throws JsonMappingException;
55
56
// Primary value serializer (with type info)
57
public abstract JsonSerializer<Object> findPrimaryPropertySerializer(JavaType valueType, BeanProperty property) throws JsonMappingException;
58
public abstract JsonSerializer<Object> findPrimaryPropertySerializer(Class<?> valueType, BeanProperty property) throws JsonMappingException;
59
60
// Typed serializers
61
public abstract JsonSerializer<Object> findTypedValueSerializer(Class<?> valueType, boolean cache, BeanProperty property) throws JsonMappingException;
62
public abstract JsonSerializer<Object> findTypedValueSerializer(JavaType valueType, boolean cache, BeanProperty property) throws JsonMappingException;
63
64
// Key serializers
65
public abstract JsonSerializer<Object> findKeySerializer(JavaType keyType, BeanProperty property) throws JsonMappingException;
66
public abstract JsonSerializer<Object> findKeySerializer(Class<?> keyType, BeanProperty property) throws JsonMappingException;
67
68
// Content serializers
69
public abstract JsonSerializer<Object> findContentValueSerializer(Class<?> valueType, BeanProperty property) throws JsonMappingException;
70
public abstract JsonSerializer<Object> findContentValueSerializer(JavaType valueType, BeanProperty property) throws JsonMappingException;
71
72
// Null serializers
73
public abstract JsonSerializer<Object> getDefaultNullKeySerializer();
74
public abstract JsonSerializer<Object> getDefaultNullValueSerializer();
75
public abstract JsonSerializer<Object> findNullKeySerializer(JavaType serializationType, BeanProperty property) throws JsonMappingException;
76
public abstract JsonSerializer<Object> findNullValueSerializer(BeanProperty property) throws JsonMappingException;
77
78
// Unknown type serializer
79
public abstract JsonSerializer<Object> getUnknownTypeSerializer(Class<?> unknownType);
80
81
// Serialization methods
82
public void serializeValue(JsonGenerator gen, Object value) throws IOException;
83
public void serializeValue(JsonGenerator gen, Object value, JavaType rootType) throws IOException;
84
public void serializeValue(JsonGenerator gen, Object value, JavaType rootType, JsonSerializer<Object> ser) throws IOException;
85
public void defaultSerializeValue(JsonGenerator gen, Object value) throws IOException;
86
public void defaultSerializeField(String fieldName, Object value, JsonGenerator gen) throws IOException;
87
public void defaultSerializeNull(JsonGenerator gen) throws IOException;
88
89
// Polymorphic serialization
90
public void defaultSerializeValue(JsonGenerator gen, Object value, JavaType type) throws IOException;
91
92
// Exception handling
93
public void reportMappingProblem(String msg, Object... msgArgs) throws JsonMappingException;
94
public <T> T reportBadTypeDefinition(BeanDescription bean, String msg, Object... msgArgs) throws JsonMappingException;
95
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop, String message, Object... msgArgs) throws JsonMappingException;
96
97
// Configuration access
98
public abstract SerializationConfig getConfig();
99
100
// Filtering
101
public abstract FilterProvider getFilterProvider();
102
103
// View support
104
public final boolean isEnabled(MapperFeature feature);
105
public final boolean isEnabled(SerializationFeature feature);
106
public final boolean canOverrideAccessModifiers();
107
108
// Generator access
109
public JsonGenerator getGenerator();
110
111
// Attributes
112
public abstract Object getAttribute(Object key);
113
public abstract SerializerProvider setAttribute(Object key, Object value);
114
115
// Type factory access
116
public final TypeFactory getTypeFactory();
117
118
// Root name handling
119
public PropertyName findRootName(JavaType rootType);
120
public PropertyName findRootName(Class<?> rawRootType);
121
122
// Cached serializers
123
public abstract boolean hasSerializerFor(Class<?> cls, AtomicReference<Throwable> cause);
124
125
// Format-specific
126
public WritableObjectId findObjectId(Object forPojo, ObjectIdGenerator<?> generatorType);
127
128
// Date handling
129
public DateFormat getDateFormat();
130
public boolean hasDateFormat();
131
public Locale getLocale();
132
public TimeZone getTimeZone();
133
}
134
```
135
136
## Standard Serializers
137
138
Jackson provides standard serializers for common Java types.
139
140
### StdSerializer
141
142
```java { .api }
143
public abstract class StdSerializer<T> extends JsonSerializer<T> implements JsonFormatVisitable, Serializable {
144
// Construction
145
protected StdSerializer(Class<T> t);
146
protected StdSerializer(JavaType type);
147
protected StdSerializer(Class<?> t, boolean dummy);
148
protected StdSerializer(StdSerializer<?> src);
149
150
// Type information
151
public Class<T> handledType();
152
153
// Schema support
154
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException;
155
public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException;
156
public JsonNode getSchema(SerializerProvider provider, Type typeHint, boolean isOptional) throws JsonMappingException;
157
158
// Utility methods for subclasses
159
protected void visitStringFormat(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException;
160
protected void visitStringFormat(JsonFormatVisitorWrapper visitor, JavaType typeHint, JsonValueFormat format) throws JsonMappingException;
161
protected void visitIntFormat(JsonFormatVisitorWrapper visitor, JavaType typeHint, JsonParser.NumberType numberType) throws JsonMappingException;
162
protected void visitIntFormat(JsonFormatVisitorWrapper visitor, JavaType typeHint, JsonParser.NumberType numberType, JsonValueFormat format) throws JsonMappingException;
163
protected void visitFloatFormat(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException;
164
protected boolean isDefaultSerializer(JsonSerializer<?> serializer);
165
166
// Exception creation helpers
167
protected JsonMappingException wrapAndThrow(SerializerProvider provider, Throwable t, Object bean, String fieldName) throws JsonMappingException;
168
protected JsonMappingException wrapAndThrow(SerializerProvider provider, Throwable t, Object bean, int index) throws JsonMappingException;
169
}
170
171
// Scalar serializers
172
public abstract class StdScalarSerializer<T> extends StdSerializer<T> {
173
protected StdScalarSerializer(Class<T> t);
174
protected StdScalarSerializer(Class<?> t, boolean dummy);
175
176
public void serializeWithType(T value, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer) throws IOException;
177
}
178
```
179
180
### Container Serializers
181
182
```java { .api }
183
public abstract class ContainerSerializer<T> extends StdSerializer<T> {
184
protected ContainerSerializer(Class<T> t);
185
protected ContainerSerializer(Class<?> t, boolean dummy);
186
protected ContainerSerializer(JavaType fullType);
187
protected ContainerSerializer(ContainerSerializer<?> src);
188
189
// Container-specific methods
190
public abstract boolean hasSingleElement(T value);
191
public abstract boolean isEmpty(SerializerProvider prov, T value);
192
193
// Content serializer access
194
protected abstract JsonSerializer<?> _withValueTypeSerializer(TypeSerializer vts);
195
}
196
197
// Array serializer
198
public class ObjectArraySerializer extends ArraySerializerBase<Object[]> {
199
public ObjectArraySerializer(JavaType elemType, boolean staticTyping, TypeSerializer vts, JsonSerializer<Object> elementSerializer);
200
public JsonSerializer<?> _withValueTypeSerializer(TypeSerializer vts);
201
public ContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts);
202
public void serializeContents(Object[] value, JsonGenerator gen, SerializerProvider provider) throws IOException;
203
public JsonNode getSchema(SerializerProvider provider, Type typeHint);
204
}
205
206
// Collection serializers
207
public class CollectionSerializer extends AsArraySerializerBase<Collection<?>> {
208
public CollectionSerializer(JavaType elemType, boolean staticTyping, TypeSerializer vts, JsonSerializer<Object> valueSerializer);
209
public ContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts);
210
public void serialize(Collection<?> value, JsonGenerator gen, SerializerProvider provider) throws IOException;
211
public void serializeContents(Collection<?> value, JsonGenerator gen, SerializerProvider provider) throws IOException;
212
}
213
214
// Map serializer
215
public class MapSerializer extends ContainerSerializer<Map<?, ?>> implements ContextualSerializer {
216
public MapSerializer(Set<String> ignoredEntries, JavaType keyType, JavaType valueType, boolean valueTypeIsStatic, TypeSerializer vts, JsonSerializer<?> keySerializer, JsonSerializer<?> valueSerializer);
217
public ContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts);
218
public MapSerializer withResolved(BeanProperty property, JsonSerializer<?> keySerializer, JsonSerializer<?> valueSerializer, Set<String> ignored, boolean sortKeys);
219
public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException;
220
public void serialize(Map<?, ?> value, JsonGenerator gen, SerializerProvider provider) throws IOException;
221
public void serializeOptionalFields(Map<?, ?> value, JsonGenerator gen, SerializerProvider provider, Object suppressableValue) throws IOException;
222
public void serializeFields(Map<?, ?> value, JsonGenerator gen, SerializerProvider provider) throws IOException;
223
public void serializeFieldsUsing(Map<?, ?> value, JsonGenerator gen, SerializerProvider provider, JsonSerializer<Object> ser) throws IOException;
224
}
225
```
226
227
## Bean Serialization
228
229
### BeanSerializer
230
231
```java { .api }
232
public class BeanSerializer extends BeanSerializerBase implements Serializable {
233
// Construction
234
public BeanSerializer(JavaType type, BeanSerializerBuilder builder, BeanPropertyWriter[] properties, BeanPropertyWriter[] filteredProperties);
235
protected BeanSerializer(BeanSerializerBase src, ObjectIdWriter objectIdWriter);
236
protected BeanSerializer(BeanSerializerBase src, ObjectIdWriter objectIdWriter, Object filterId);
237
protected BeanSerializer(BeanSerializerBase src, Set<String> toIgnore, Set<String> toInclude);
238
239
// Factory methods
240
public static BeanSerializer createDummy(JavaType forType);
241
242
// Serialization
243
public void serialize(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException;
244
protected void serializeFields(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException;
245
protected void serializeFieldsFiltered(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException;
246
247
// String representation
248
public String toString();
249
}
250
251
public abstract class BeanSerializerBase extends StdSerializer<Object> implements ContextualSerializer, ResolvableSerializer, JsonFormatVisitable, Serializable {
252
// Property writers
253
protected final BeanPropertyWriter[] _props;
254
protected final BeanPropertyWriter[] _filteredProps;
255
256
// Special properties
257
protected final AnyGetterWriter _anyGetterWriter;
258
protected final Object _propertyFilterId;
259
protected final AnnotatedMember _typeIdDef;
260
261
// Object identity
262
protected final ObjectIdWriter _objectIdWriter;
263
264
// Shape and features
265
protected final JsonFormat.Shape _serializationShape;
266
267
// Construction
268
protected BeanSerializerBase(JavaType type, BeanSerializerBuilder builder, BeanPropertyWriter[] properties, BeanPropertyWriter[] filteredProperties);
269
protected BeanSerializerBase(BeanSerializerBase src, BeanPropertyWriter[] properties, BeanPropertyWriter[] filteredProperties);
270
protected BeanSerializerBase(BeanSerializerBase src, ObjectIdWriter objectIdWriter);
271
protected BeanSerializerBase(BeanSerializerBase src, ObjectIdWriter objectIdWriter, Object filterId);
272
protected BeanSerializerBase(BeanSerializerBase src, Set<String> toIgnore, Set<String> toInclude);
273
274
// Abstract serialization methods
275
public abstract void serialize(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException;
276
protected abstract void serializeFields(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException;
277
protected abstract void serializeFieldsFiltered(Object bean, JsonGenerator gen, SerializerProvider provider) throws IOException;
278
279
// Metadata
280
public boolean usesObjectId();
281
282
// Contextualization
283
public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException;
284
285
// Resolution
286
public void resolve(SerializerProvider provider) throws JsonMappingException;
287
288
// Schema support
289
public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException;
290
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException;
291
}
292
```
293
294
### BeanPropertyWriter
295
296
```java { .api }
297
public class BeanPropertyWriter extends PropertyWriter implements Serializable {
298
// Property metadata
299
protected final SerializedString _name;
300
protected final PropertyName _wrapperName;
301
protected final JavaType _declaredType;
302
protected final JavaType _cfgSerializationType;
303
protected final AnnotatedMember _member;
304
protected final BeanProperty.Std _internalSettings;
305
306
// Serialization
307
protected JsonSerializer<Object> _serializer;
308
protected JsonSerializer<Object> _nullSerializer;
309
protected TypeSerializer _typeSerializer;
310
311
// Filtering and inclusion
312
protected Class<?>[] _includeInViews;
313
protected PropertyFilter _filter;
314
protected Object _suppressableValue;
315
protected boolean _suppressNulls;
316
317
// Construction
318
public BeanPropertyWriter(BeanPropertyDefinition propDef, AnnotatedMember member, Annotations contextAnnotations, JavaType declaredType, JsonSerializer<?> ser, TypeSerializer typeSer, JavaType serType, boolean suppressNulls, Object suppressableValue, Class<?>[] includeInViews);
319
protected BeanPropertyWriter(BeanPropertyWriter base, PropertyName name);
320
protected BeanPropertyWriter(BeanPropertyWriter base, JsonSerializer<?> ser);
321
322
// Factory methods
323
public BeanPropertyWriter rename(PropertyName newName);
324
public BeanPropertyWriter withSerializer(JsonSerializer<?> ser);
325
public BeanPropertyWriter withNullSerializer(JsonSerializer<?> nullSer);
326
327
// Assignment
328
public void assignSerializer(JsonSerializer<Object> ser);
329
public void assignNullSerializer(JsonSerializer<Object> nullSer);
330
public void assignTypeSerializer(TypeSerializer typeSer);
331
332
// Serialization
333
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception;
334
public void serializeAsOmittedField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception;
335
public void serializeAsElement(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception;
336
public void serializeAsPlaceholder(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception;
337
338
// Value access
339
public Object get(Object bean) throws Exception;
340
public void set(Object bean, Object value) throws Exception;
341
342
// Property information
343
public String getName();
344
public PropertyName getFullName();
345
public JavaType getType();
346
public PropertyName getWrapperName();
347
public AnnotatedMember getMember();
348
public <A extends Annotation> A getAnnotation(Class<A> acls);
349
public <A extends Annotation> A getContextAnnotation(Class<A> acls);
350
351
// Filtering and views
352
public boolean willSuppressNulls();
353
public Class<?>[] getViews();
354
355
// Schema support
356
public void depositSchemaProperty(JsonObjectFormatVisitor objectVisitor, SerializerProvider provider) throws JsonMappingException;
357
358
// String representation
359
public String toString();
360
}
361
```
362
363
## Serializer Factory
364
365
### SerializerFactory
366
367
```java { .api }
368
public abstract class SerializerFactory {
369
// Serializer creation
370
public abstract JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException;
371
public abstract JsonSerializer<Object> createKeySerializer(SerializerProvider prov, JavaType type, JsonSerializer<Object> defaultImpl) throws JsonMappingException;
372
373
// Type serializer creation
374
public abstract TypeSerializer createTypeSerializer(SerializationConfig config, JavaType baseType) throws JsonMappingException;
375
376
// Configuration
377
public abstract SerializerFactory withAdditionalSerializers(Serializers additional);
378
public abstract SerializerFactory withAdditionalKeySerializers(Serializers additional);
379
public abstract SerializerFactory withSerializerModifier(BeanSerializerModifier modifier);
380
public abstract SerializerFactory withConfig(SerializationConfig config);
381
}
382
383
public class BeanSerializerFactory extends BasicSerializerFactory implements Serializable {
384
// Singleton instance
385
public static final BeanSerializerFactory instance;
386
387
// Construction
388
public BeanSerializerFactory(SerializerFactoryConfig config);
389
390
// Factory methods
391
public SerializerFactory withConfig(SerializationConfig config);
392
public SerializerFactory withAdditionalSerializers(Serializers additional);
393
public SerializerFactory withAdditionalKeySerializers(Serializers additional);
394
public SerializerFactory withSerializerModifier(BeanSerializerModifier modifier);
395
396
// Serializer creation
397
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType type) throws JsonMappingException;
398
399
// Bean serializer creation
400
public JsonSerializer<Object> findBeanSerializer(SerializerProvider prov, JavaType type, BeanDescription beanDesc) throws JsonMappingException;
401
public JsonSerializer<Object> constructBeanSerializer(SerializerProvider prov, BeanDescription beanDesc) throws JsonMappingException;
402
403
// Builder creation
404
protected BeanSerializerBuilder constructBeanSerializerBuilder(BeanDescription beanDesc);
405
protected BeanSerializer createBeanSerializer(SerializerProvider prov, JavaType type, BeanDescription beanDesc, JsonFormat.Value format) throws JsonMappingException;
406
407
// Property handling
408
protected void removeIgnorableTypes(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyDefinition> properties);
409
protected void removeSetterlessGetters(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyDefinition> properties);
410
protected void addBeanProps(SerializationConfig config, BeanDescription beanDesc, BeanSerializerBuilder builder) throws JsonMappingException;
411
protected List<BeanPropertyWriter> findBeanProperties(SerializerProvider prov, BeanDescription beanDesc, BeanSerializerBuilder builder) throws JsonMappingException;
412
protected BeanPropertyWriter buildWriter(SerializerProvider prov, BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser, TypeSerializer typeSer, TypeSerializer contentTypeSer, AnnotatedMember am, boolean defaultUseStaticTyping) throws JsonMappingException;
413
414
// Filtering
415
protected PropertyFilter findPropertyFilter(SerializerProvider provider, Object filterId, Object valueToFilter) throws JsonMappingException;
416
}
417
```
418
419
## Serialization Configuration
420
421
### SerializationConfig
422
423
```java { .api }
424
public final class SerializationConfig extends MapperConfigBase<SerializationFeature, SerializationConfig> implements Serializable {
425
// Construction
426
public SerializationConfig(BaseSettings base, SubtypeResolver str, SimpleMixInResolver mixins, RootNameLookup rootNames, ConfigOverrides configOverrides);
427
428
// Configuration modification
429
public SerializationConfig with(SerializationFeature feature);
430
public SerializationConfig with(SerializationFeature first, SerializationFeature... features);
431
public SerializationConfig withFeatures(SerializationFeature... features);
432
public SerializationConfig without(SerializationFeature feature);
433
public SerializationConfig without(SerializationFeature first, SerializationFeature... features);
434
public SerializationConfig withoutFeatures(SerializationFeature... features);
435
436
// Feature checking
437
public boolean isEnabled(SerializationFeature f);
438
public int getSerializationFeatures();
439
440
// Generator configuration
441
public SerializationConfig with(JsonGenerator.Feature feature);
442
public SerializationConfig withFeatures(JsonGenerator.Feature... features);
443
public SerializationConfig without(JsonGenerator.Feature feature);
444
public SerializationConfig withoutFeatures(JsonGenerator.Feature... features);
445
446
// Other configuration
447
public SerializationConfig with(FilterProvider filters);
448
public SerializationConfig withDefaultPrettyPrinter(PrettyPrinter pp);
449
public SerializationConfig withRootName(PropertyName rootName);
450
public SerializationConfig withRootName(String rootName);
451
public SerializationConfig withView(Class<?> view);
452
453
// Access methods
454
public FilterProvider getFilterProvider();
455
public PrettyPrinter getDefaultPrettyPrinter();
456
public <T extends BeanDescription> T introspect(JavaType type);
457
458
// Serialization inclusion
459
public JsonInclude.Value getDefaultPropertyInclusion();
460
public JsonInclude.Value getDefaultPropertyInclusion(Class<?> baseType);
461
public JsonInclude.Value getDefaultInclusion(Class<?> baseType, Class<?> propertyType);
462
463
// Date format
464
public String getDateFormatPattern();
465
public DateFormat getDateFormat();
466
467
// Root name handling
468
public PropertyName findRootName(JavaType rootType);
469
public PropertyName findRootName(Class<?> rawRootType);
470
471
// View support
472
public Class<?> getActiveView();
473
474
// Attributes
475
public ContextAttributes getAttributes();
476
}
477
```
478
479
### SerializationFeature
480
481
```java { .api }
482
public enum SerializationFeature implements ConfigFeature {
483
// Wrapping and formatting
484
WRAP_ROOT_VALUE(false),
485
INDENT_OUTPUT(false),
486
487
// Error handling
488
FAIL_ON_EMPTY_BEANS(true),
489
FAIL_ON_SELF_REFERENCES(true),
490
WRAP_EXCEPTIONS(true),
491
FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS(true),
492
493
// Reference handling
494
WRITE_SELF_REFERENCES_AS_NULL(false),
495
496
// Resource management
497
CLOSE_CLOSEABLE(false),
498
FLUSH_AFTER_WRITE_VALUE(true),
499
500
// Date and time handling
501
WRITE_DATES_AS_TIMESTAMPS(true),
502
WRITE_DATE_KEYS_AS_TIMESTAMPS(false),
503
WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS(true),
504
505
// Array and character handling
506
WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS(false),
507
508
// Enum handling
509
WRITE_ENUMS_USING_TO_STRING(false),
510
WRITE_ENUMS_USING_INDEX(false),
511
WRITE_ENUM_KEYS_USING_INDEX(false),
512
513
// Map handling
514
WRITE_NULL_MAP_VALUES(true),
515
WRITE_EMPTY_JSON_ARRAYS(true),
516
WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED(false),
517
ORDER_MAP_ENTRIES_BY_KEYS(false),
518
519
// Number handling
520
WRITE_BIGDECIMAL_AS_PLAIN(false),
521
522
// Object identity
523
USE_EQUALITY_FOR_OBJECT_ID(false);
524
525
private final boolean _defaultState;
526
private final int _mask;
527
528
private SerializationFeature(boolean defaultState) {
529
_defaultState = defaultState;
530
_mask = (1 << ordinal());
531
}
532
533
public boolean enabledByDefault() {
534
return _defaultState;
535
}
536
537
public int getMask() {
538
return _mask;
539
}
540
541
public boolean enabledIn(int flags) {
542
return (flags & _mask) != 0;
543
}
544
}
545
```
546
547
## Usage Examples
548
549
### Custom Serializers
550
551
```java
552
import com.fasterxml.jackson.core.JsonGenerator;
553
import com.fasterxml.jackson.databind.SerializerProvider;
554
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
555
556
// Custom serializer for Person class
557
public class PersonSerializer extends StdSerializer<Person> {
558
559
public PersonSerializer() {
560
this(null);
561
}
562
563
public PersonSerializer(Class<Person> t) {
564
super(t);
565
}
566
567
@Override
568
public void serialize(Person person, JsonGenerator gen, SerializerProvider provider) throws IOException {
569
gen.writeStartObject();
570
gen.writeStringField("fullName", person.getFirstName() + " " + person.getLastName());
571
gen.writeNumberField("age", person.getAge());
572
573
// Custom date formatting
574
if (person.getBirthDate() != null) {
575
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
576
gen.writeStringField("birthDate", sdf.format(person.getBirthDate()));
577
}
578
579
// Conditional field
580
if (person.isActive()) {
581
gen.writeStringField("status", "ACTIVE");
582
}
583
584
gen.writeEndObject();
585
}
586
587
// Optional: provide schema information
588
@Override
589
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
590
JsonObjectFormatVisitor objectVisitor = visitor.expectObjectFormat(typeHint);
591
if (objectVisitor != null) {
592
objectVisitor.property("fullName", JsonFormatTypes.STRING);
593
objectVisitor.property("age", JsonFormatTypes.INTEGER);
594
objectVisitor.optionalProperty("birthDate", JsonFormatTypes.STRING);
595
objectVisitor.optionalProperty("status", JsonFormatTypes.STRING);
596
}
597
}
598
}
599
600
// Register with ObjectMapper
601
ObjectMapper mapper = new ObjectMapper();
602
SimpleModule module = new SimpleModule();
603
module.addSerializer(Person.class, new PersonSerializer());
604
mapper.registerModule(module);
605
606
// Use
607
Person person = new Person("John", "Doe", 30);
608
String json = mapper.writeValueAsString(person);
609
// Result: {"fullName":"John Doe","age":30,"status":"ACTIVE"}
610
```
611
612
### Contextual Serializers
613
614
```java
615
// Contextual serializer that adapts based on property annotations
616
public class MoneySerializer extends StdSerializer<Money> implements ContextualSerializer {
617
618
private final String currency;
619
private final boolean showSymbol;
620
621
public MoneySerializer() {
622
this(null, false);
623
}
624
625
private MoneySerializer(String currency, boolean showSymbol) {
626
super(Money.class);
627
this.currency = currency;
628
this.showSymbol = showSymbol;
629
}
630
631
@Override
632
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
633
if (property != null) {
634
CurrencyFormat ann = property.getAnnotation(CurrencyFormat.class);
635
if (ann != null) {
636
return new MoneySerializer(ann.currency(), ann.showSymbol());
637
}
638
}
639
return this;
640
}
641
642
@Override
643
public void serialize(Money money, JsonGenerator gen, SerializerProvider serializers) throws IOException {
644
if (showSymbol) {
645
String symbol = getCurrencySymbol(currency != null ? currency : money.getCurrency());
646
gen.writeString(symbol + money.getAmount());
647
} else {
648
gen.writeNumber(money.getAmount());
649
}
650
}
651
652
private String getCurrencySymbol(String currency) {
653
return switch (currency) {
654
case "USD" -> "$";
655
case "EUR" -> "€";
656
case "GBP" -> "£";
657
default -> currency + " ";
658
};
659
}
660
}
661
662
// Custom annotation
663
@Retention(RetentionPolicy.RUNTIME)
664
@Target(ElementType.FIELD)
665
public @interface CurrencyFormat {
666
String currency() default "";
667
boolean showSymbol() default false;
668
}
669
670
// Usage in POJO
671
public class Product {
672
private String name;
673
674
@CurrencyFormat(currency = "USD", showSymbol = true)
675
private Money price;
676
677
@CurrencyFormat(currency = "USD", showSymbol = false)
678
private Money cost;
679
680
// getters/setters
681
}
682
```
683
684
### Container Serializers
685
686
```java
687
// Custom collection serializer
688
public class PagedResultSerializer extends ContainerSerializer<PagedResult<?>> {
689
690
private final JavaType elementType;
691
private final JsonSerializer<Object> elementSerializer;
692
693
public PagedResultSerializer(JavaType elementType, JsonSerializer<Object> elementSerializer) {
694
super(PagedResult.class);
695
this.elementType = elementType;
696
this.elementSerializer = elementSerializer;
697
}
698
699
@Override
700
public void serialize(PagedResult<?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
701
gen.writeStartObject();
702
gen.writeArrayFieldStart("items");
703
704
for (Object item : value.getItems()) {
705
if (elementSerializer != null) {
706
elementSerializer.serialize(item, gen, serializers);
707
} else {
708
serializers.defaultSerializeValue(item, gen);
709
}
710
}
711
712
gen.writeEndArray();
713
gen.writeNumberField("totalCount", value.getTotalCount());
714
gen.writeNumberField("pageNumber", value.getPageNumber());
715
gen.writeNumberField("pageSize", value.getPageSize());
716
gen.writeBooleanField("hasNext", value.isHasNext());
717
gen.writeEndObject();
718
}
719
720
@Override
721
public boolean hasSingleElement(PagedResult<?> value) {
722
return value.getItems().size() == 1;
723
}
724
725
@Override
726
public boolean isEmpty(SerializerProvider prov, PagedResult<?> value) {
727
return value.getItems().isEmpty();
728
}
729
730
@Override
731
protected JsonSerializer<?> _withValueTypeSerializer(TypeSerializer vts) {
732
// Return new instance with type serializer if needed
733
return this;
734
}
735
}
736
```
737
738
### Bean Property Writers
739
740
```java
741
// Custom property writer for computed fields
742
public class ComputedPropertyWriter extends BeanPropertyWriter {
743
744
private final Function<Object, Object> computer;
745
746
public ComputedPropertyWriter(BeanPropertyDefinition propDef, AnnotatedMember member,
747
Function<Object, Object> computer) {
748
super(propDef, member, null, propDef.getPrimaryType(), null, null,
749
propDef.getPrimaryType(), false, null, null);
750
this.computer = computer;
751
}
752
753
@Override
754
public Object get(Object bean) throws Exception {
755
// Compute value dynamically
756
return computer.apply(bean);
757
}
758
759
@Override
760
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
761
Object value = get(bean);
762
if (value == null) {
763
if (_nullSerializer != null) {
764
gen.writeFieldName(_name);
765
_nullSerializer.serialize(null, gen, prov);
766
}
767
} else {
768
gen.writeFieldName(_name);
769
if (_serializer == null) {
770
prov.defaultSerializeValue(value, gen);
771
} else {
772
_serializer.serialize(value, gen, prov);
773
}
774
}
775
}
776
}
777
778
// Usage in custom bean serializer modifier
779
public class ComputedFieldSerializerModifier extends BeanSerializerModifier {
780
781
@Override
782
public BeanSerializerBuilder updateBuilder(SerializationConfig config, BeanDescription beanDesc, BeanSerializerBuilder builder) {
783
// Add computed properties
784
if (beanDesc.getBeanClass() == Person.class) {
785
// Add fullName computed field
786
SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(
787
config, null, new PropertyName("fullName"), PropertyMetadata.STD_REQUIRED_OR_OPTIONAL);
788
789
ComputedPropertyWriter writer = new ComputedPropertyWriter(propDef, null,
790
bean -> {
791
Person person = (Person) bean;
792
return person.getFirstName() + " " + person.getLastName();
793
});
794
795
builder.addProperty(writer);
796
}
797
return builder;
798
}
799
}
800
```
801
802
### Filter Support
803
804
```java
805
// Custom property filter
806
public class DynamicPropertyFilter implements PropertyFilter {
807
808
private final Set<String> allowedFields;
809
private final Predicate<Object> condition;
810
811
public DynamicPropertyFilter(Set<String> allowedFields, Predicate<Object> condition) {
812
this.allowedFields = allowedFields;
813
this.condition = condition;
814
}
815
816
@Override
817
public void serializeAsField(Object pojo, JsonGenerator gen, SerializerProvider prov, PropertyWriter writer) throws Exception {
818
if (include(writer.getName(), pojo)) {
819
writer.serializeAsField(pojo, gen, prov);
820
} else {
821
writer.serializeAsOmittedField(pojo, gen, prov);
822
}
823
}
824
825
@Override
826
public void serializeAsElement(Object elementValue, JsonGenerator gen, SerializerProvider prov, PropertyWriter writer) throws Exception {
827
writer.serializeAsElement(elementValue, gen, prov);
828
}
829
830
@Override
831
public void depositSchemaProperty(PropertyWriter writer, ObjectNode propertiesNode, SerializerProvider provider) throws JsonMappingException {
832
writer.depositSchemaProperty(propertiesNode, provider);
833
}
834
835
private boolean include(String fieldName, Object pojo) {
836
return allowedFields.contains(fieldName) && condition.test(pojo);
837
}
838
}
839
840
// Usage with FilterProvider
841
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
842
filterProvider.addFilter("dynamicFilter", new DynamicPropertyFilter(
843
Set.of("name", "age", "email"),
844
obj -> ((Person) obj).isActive()
845
));
846
847
ObjectMapper mapper = new ObjectMapper();
848
mapper.setFilterProvider(filterProvider);
849
850
// POJO with filter annotation
851
@JsonFilter("dynamicFilter")
852
public class Person {
853
// fields and methods
854
}
855
```
856
857
### Serialization Features Configuration
858
859
```java
860
ObjectMapper mapper = new ObjectMapper();
861
862
// Configure serialization features
863
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
864
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
865
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
866
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
867
868
// Multiple features at once
869
mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,
870
SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
871
872
mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES,
873
SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
874
875
// Check feature status
876
boolean indented = mapper.isEnabled(SerializationFeature.INDENT_OUTPUT);
877
boolean timestampsAsNumbers = mapper.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
878
879
// Configure through ObjectWriter
880
ObjectWriter writer = mapper.writer()
881
.with(SerializationFeature.INDENT_OUTPUT)
882
.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
883
.withDefaultPrettyPrinter();
884
885
String json = writer.writeValueAsString(object);
886
```
887
888
## Types
889
890
```java { .api }
891
// Serializer interfaces
892
public interface ContextualSerializer {
893
JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException;
894
}
895
896
public interface ResolvableSerializer {
897
void resolve(SerializerProvider provider) throws JsonMappingException;
898
}
899
900
// Property writer base
901
public abstract class PropertyWriter implements BeanProperty {
902
public abstract void serializeAsField(Object value, JsonGenerator gen, SerializerProvider prov) throws Exception;
903
public abstract void serializeAsOmittedField(Object value, JsonGenerator gen, SerializerProvider prov) throws Exception;
904
public abstract void serializeAsElement(Object value, JsonGenerator gen, SerializerProvider prov) throws Exception;
905
public void serializeAsPlaceholder(Object value, JsonGenerator gen, SerializerProvider prov) throws Exception;
906
public abstract void depositSchemaProperty(JsonObjectFormatVisitor v, SerializerProvider provider) throws JsonMappingException;
907
}
908
909
// Serializer cache
910
public final class SerializerCache {
911
public int cachedSerializersCount();
912
public void flushCachedSerializers();
913
public JsonSerializer<Object> untypedValueSerializer(Class<?> type);
914
public JsonSerializer<Object> untypedValueSerializer(JavaType type);
915
public ReadOnlyClassToSerializerMap getReadOnlyLookupMap();
916
}
917
918
// Serializer registration interface
919
public interface Serializers {
920
JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type, BeanDescription beanDesc);
921
JsonSerializer<?> findReferenceSerializer(SerializationConfig config, ReferenceType type, BeanDescription beanDesc, TypeSerializer contentTypeSerializer, JsonSerializer<Object> contentValueSerializer);
922
JsonSerializer<?> findArraySerializer(SerializationConfig config, ArrayType type, BeanDescription beanDesc, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer);
923
JsonSerializer<?> findCollectionSerializer(SerializationConfig config, CollectionType type, BeanDescription beanDesc, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer);
924
JsonSerializer<?> findCollectionLikeSerializer(SerializationConfig config, CollectionLikeType type, BeanDescription beanDesc, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer);
925
JsonSerializer<?> findMapSerializer(SerializationConfig config, MapType type, BeanDescription beanDesc, JsonSerializer<Object> keySerializer, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer);
926
JsonSerializer<?> findMapLikeSerializer(SerializationConfig config, MapLikeType type, BeanDescription beanDesc, JsonSerializer<Object> keySerializer, TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer);
927
928
public abstract static class Base implements Serializers {
929
// Default implementations returning null
930
}
931
}
932
933
// Bean serializer modifier
934
public abstract class BeanSerializerModifier {
935
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties);
936
public List<BeanPropertyWriter> orderProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties);
937
public BeanSerializerBuilder updateBuilder(SerializationConfig config, BeanDescription beanDesc, BeanSerializerBuilder builder);
938
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer);
939
public JsonSerializer<?> modifyArraySerializer(SerializationConfig config, ArrayType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
940
public JsonSerializer<?> modifyCollectionSerializer(SerializationConfig config, CollectionType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
941
public JsonSerializer<?> modifyCollectionLikeSerializer(SerializationConfig config, CollectionLikeType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
942
public JsonSerializer<?> modifyMapSerializer(SerializationConfig config, MapType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
943
public JsonSerializer<?> modifyMapLikeSerializer(SerializationConfig config, MapLikeType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
944
public JsonSerializer<?> modifyEnumSerializer(SerializationConfig config, JavaType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
945
public JsonSerializer<?> modifyKeySerializer(SerializationConfig config, JavaType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer);
946
}
947
```