0
# Configuration
1
2
Jackson Databind provides extensive configuration capabilities through features, settings, and overrides that control serialization and deserialization behavior. The configuration system includes feature enums, configuration classes, and builder patterns for fine-grained control over JSON processing.
3
4
## Configuration Features
5
6
Jackson uses enum-based feature flags for configuration. Features are grouped into different categories based on their scope and purpose.
7
8
### MapperFeature
9
10
MapperFeature defines features that affect general mapper behavior and configuration.
11
12
```java { .api }
13
public enum MapperFeature implements ConfigFeature {
14
// Annotation processing
15
USE_ANNOTATIONS(true),
16
17
// Creator detection
18
AUTO_DETECT_CREATORS(true),
19
AUTO_DETECT_FIELDS(true),
20
AUTO_DETECT_GETTERS(true),
21
AUTO_DETECT_IS_GETTERS(true),
22
AUTO_DETECT_SETTERS(true),
23
24
// Access modifier handling
25
REQUIRE_SETTERS_FOR_GETTERS(false),
26
ALLOW_FINAL_FIELDS_AS_MUTATORS(false),
27
INFER_PROPERTY_MUTATORS(true),
28
INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES(true),
29
30
// Case sensitivity
31
ACCEPT_CASE_INSENSITIVE_PROPERTIES(false),
32
ACCEPT_CASE_INSENSITIVE_ENUMS(false),
33
ACCEPT_CASE_INSENSITIVE_VALUES(false),
34
35
// Static typing
36
USE_STATIC_TYPING(false),
37
38
// Base64 handling
39
USE_BASE64_VARIANT_FOR_BINARY(false),
40
41
// Getter behavior
42
DEFAULT_VIEW_INCLUSION(true),
43
SORT_PROPERTIES_ALPHABETICALLY(false),
44
45
// Visibility
46
OVERRIDE_PUBLIC_ACCESS_MODIFIERS(true),
47
48
// Coercion
49
USE_STD_BEAN_NAMING(false),
50
ALLOW_VOID_VALUED_PROPERTIES(false),
51
52
// Property inclusion
53
CAN_OVERRIDE_ACCESS_MODIFIERS(true),
54
55
// Constructor properties
56
INFER_BUILDER_TYPE_BINDINGS(true),
57
58
// Propagate transient marker
59
PROPAGATE_TRANSIENT_MARKER(false),
60
61
// Block unsafe polymorphic base types
62
BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES(false),
63
64
// Apply default values
65
APPLY_DEFAULT_VALUES(false);
66
67
private final boolean _defaultState;
68
private final int _mask;
69
70
private MapperFeature(boolean defaultState) {
71
_defaultState = defaultState;
72
_mask = (1 << ordinal());
73
}
74
75
public boolean enabledByDefault() {
76
return _defaultState;
77
}
78
79
public int getMask() {
80
return _mask;
81
}
82
83
public boolean enabledIn(int flags) {
84
return (flags & _mask) != 0;
85
}
86
}
87
```
88
89
### SerializationFeature
90
91
SerializationFeature controls serialization behavior (covered in detail in serialization.md).
92
93
```java { .api }
94
public enum SerializationFeature implements ConfigFeature {
95
WRAP_ROOT_VALUE(false),
96
INDENT_OUTPUT(false),
97
FAIL_ON_EMPTY_BEANS(true),
98
FAIL_ON_SELF_REFERENCES(true),
99
WRAP_EXCEPTIONS(true),
100
FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS(true),
101
WRITE_SELF_REFERENCES_AS_NULL(false),
102
CLOSE_CLOSEABLE(false),
103
FLUSH_AFTER_WRITE_VALUE(true),
104
WRITE_DATES_AS_TIMESTAMPS(true),
105
WRITE_DATE_KEYS_AS_TIMESTAMPS(false),
106
WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS(false),
107
WRITE_ENUMS_USING_TO_STRING(false),
108
WRITE_ENUMS_USING_INDEX(false),
109
WRITE_ENUM_KEYS_USING_INDEX(false),
110
WRITE_NULL_MAP_VALUES(true),
111
WRITE_EMPTY_JSON_ARRAYS(true),
112
WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED(false),
113
WRITE_BIGDECIMAL_AS_PLAIN(false),
114
WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS(true),
115
ORDER_MAP_ENTRIES_BY_KEYS(false),
116
USE_EQUALITY_FOR_OBJECT_ID(false);
117
118
// Implementation similar to MapperFeature
119
}
120
```
121
122
### DeserializationFeature
123
124
DeserializationFeature controls deserialization behavior (covered in detail in deserialization.md).
125
126
```java { .api }
127
public enum DeserializationFeature implements ConfigFeature {
128
USE_BIG_DECIMAL_FOR_FLOATS(false),
129
USE_BIG_INTEGER_FOR_INTS(false),
130
USE_LONG_FOR_INTS(false),
131
USE_JAVA_ARRAY_FOR_JSON_ARRAY(false),
132
FAIL_ON_UNKNOWN_PROPERTIES(true),
133
FAIL_ON_NULL_FOR_PRIMITIVES(false),
134
FAIL_ON_NUMBERS_FOR_ENUMS(false),
135
FAIL_ON_INVALID_SUBTYPE(true),
136
FAIL_ON_READING_DUP_TREE_KEY(false),
137
FAIL_ON_IGNORED_PROPERTIES(false),
138
FAIL_ON_UNRESOLVED_OBJECT_IDS(true),
139
FAIL_ON_MISSING_CREATOR_PROPERTIES(false),
140
FAIL_ON_NULL_CREATOR_PROPERTIES(false),
141
FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY(true),
142
FAIL_ON_TRAILING_TOKENS(false),
143
WRAP_EXCEPTIONS(true),
144
ACCEPT_SINGLE_VALUE_AS_ARRAY(false),
145
UNWRAP_SINGLE_VALUE_ARRAYS(false),
146
UNWRAP_ROOT_VALUE(false),
147
ACCEPT_EMPTY_STRING_AS_NULL_OBJECT(false),
148
ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT(false),
149
ACCEPT_FLOAT_AS_INT(true),
150
READ_ENUMS_USING_TO_STRING(false),
151
READ_UNKNOWN_ENUM_VALUES_AS_NULL(false),
152
READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE(false),
153
READ_DATE_TIMESTAMPS_AS_NANOSECONDS(true),
154
ADJUST_DATES_TO_CONTEXT_TIME_ZONE(true),
155
EAGER_DESERIALIZER_FETCH(true);
156
157
// Implementation similar to MapperFeature
158
}
159
```
160
161
## Base Configuration Classes
162
163
### MapperConfig
164
165
MapperConfig is the base class for mapper configuration objects.
166
167
```java { .api }
168
public abstract class MapperConfig<T> implements ClassIntrospector.MixInResolver, Serializable {
169
// Feature checking
170
public final boolean isEnabled(MapperFeature f);
171
public final boolean isEnabled(JsonFactory.Feature f);
172
public final boolean hasMapperFeatures(int featureMask);
173
public final boolean hasSomeOfFeatures(int featureMask);
174
175
// Settings access
176
public final BaseSettings getBase();
177
public final AnnotationIntrospector getAnnotationIntrospector();
178
public final VisibilityChecker<?> getDefaultVisibilityChecker();
179
public SubtypeResolver getSubtypeResolver();
180
public final PropertyNamingStrategy getPropertyNamingStrategy();
181
public final HandlerInstantiator getHandlerInstantiator();
182
public final TypeResolverBuilder<?> getDefaultTyper();
183
184
// Type factory
185
public final TypeFactory getTypeFactory();
186
187
// Access control
188
public final boolean canOverrideAccessModifiers();
189
public final boolean shouldSortPropertiesAlphabetically();
190
191
// Locale and timezone
192
public final Locale getLocale();
193
public final TimeZone getTimeZone();
194
195
// Property inclusion
196
public abstract JsonInclude.Value getDefaultPropertyInclusion();
197
public abstract JsonInclude.Value getDefaultPropertyInclusion(Class<?> baseType);
198
public JsonInclude.Value getDefaultInclusion(Class<?> baseType, Class<?> propertyType);
199
200
// Configuration overrides
201
public final ConfigOverride findConfigOverride(Class<?> type);
202
public final ConfigOverride getConfigOverride(Class<?> type);
203
public final JsonInclude.Value getDefaultPropertyInclusion(Class<?> baseType, JsonInclude.Value defaultIncl);
204
public final JsonFormat.Value getDefaultPropertyFormat(Class<?> type);
205
public final VisibilityChecker<?> getDefaultVisibilityChecker(Class<?> forClass, VisibilityChecker<?> defaultVc);
206
207
// Mix-in support (from MixInResolver)
208
public final Class<?> findMixInClassFor(Class<?> cls);
209
public final int mixInCount();
210
211
// Root name handling
212
public abstract PropertyName findRootName(JavaType rootType);
213
public abstract PropertyName findRootName(Class<?> rawRootType);
214
215
// View support
216
public final Class<?> getActiveView();
217
218
// Context attributes
219
public abstract ContextAttributes getAttributes();
220
221
// Introspection
222
public final ClassIntrospector getClassIntrospector();
223
224
// Problem handlers (for deserialization config)
225
public abstract boolean useRootWrapping();
226
227
// Date format
228
public final DateFormat getDateFormat();
229
230
// Constructor detector
231
public final ConstructorDetector getConstructorDetector();
232
233
// Coercion configs
234
public final CoercionConfigs getCoercionConfigs();
235
}
236
```
237
238
### BaseSettings
239
240
BaseSettings contains shared configuration settings.
241
242
```java { .api }
243
public final class BaseSettings implements Serializable {
244
// Construction
245
public BaseSettings(ClassIntrospector ci, AnnotationIntrospector ai, VisibilityChecker<?> vc, PropertyNamingStrategy pns, TypeFactory tf, TypeResolverBuilder<?> typer, DateFormat dateFormat, HandlerInstantiator hi, Locale locale, TimeZone tz, Base64Variant base64);
246
247
// Component access
248
public ClassIntrospector getClassIntrospector();
249
public AnnotationIntrospector getAnnotationIntrospector();
250
public PropertyNamingStrategy getPropertyNamingStrategy();
251
public TypeFactory getTypeFactory();
252
public TypeResolverBuilder<?> getTypeResolverBuilder();
253
public DateFormat getDateFormat();
254
public HandlerInstantiator getHandlerInstantiator();
255
public Locale getLocale();
256
public TimeZone getTimeZone();
257
public VisibilityChecker<?> getDefaultVisibilityChecker();
258
public Base64Variant getBase64Variant();
259
260
// Modification methods
261
public BaseSettings withClassIntrospector(ClassIntrospector ci);
262
public BaseSettings withAnnotationIntrospector(AnnotationIntrospector ai);
263
public BaseSettings withInsertedAnnotationIntrospector(AnnotationIntrospector ai);
264
public BaseSettings withAppendedAnnotationIntrospector(AnnotationIntrospector ai);
265
public BaseSettings withVisibilityChecker(VisibilityChecker<?> vc);
266
public BaseSettings withPropertyNamingStrategy(PropertyNamingStrategy pns);
267
public BaseSettings withTypeFactory(TypeFactory tf);
268
public BaseSettings withTypeResolverBuilder(TypeResolverBuilder<?> typer);
269
public BaseSettings withDateFormat(DateFormat df);
270
public BaseSettings withHandlerInstantiator(HandlerInstantiator hi);
271
public BaseSettings withLocale(Locale l);
272
public BaseSettings withTimeZone(TimeZone tz);
273
public BaseSettings withBase64Variant(Base64Variant base64);
274
}
275
```
276
277
## Configuration Overrides
278
279
### ConfigOverride
280
281
ConfigOverride allows per-type configuration overrides.
282
283
```java { .api }
284
public abstract class ConfigOverride {
285
// Format override
286
public JsonFormat.Value getFormat();
287
288
// Inclusion override
289
public JsonInclude.Value getInclude();
290
public JsonInclude.Value getIncludeAsProperty();
291
292
// Ignored properties
293
public JsonIgnoreProperties.Value getIgnorals();
294
295
// Setter configuration
296
public JsonSetter.Value getSetterInfo();
297
298
// Visibility
299
public VisibilityChecker.Std getVisibility();
300
301
// Mergeable info
302
public Boolean getMergeable();
303
304
// Null handling
305
public JsonSetter.Value getNullHandling();
306
}
307
308
public class MutableConfigOverride extends ConfigOverride {
309
// Modification methods
310
public MutableConfigOverride setFormat(JsonFormat.Value v);
311
public MutableConfigOverride setInclude(JsonInclude.Value v);
312
public MutableConfigOverride setIncludeAsProperty(JsonInclude.Value v);
313
public MutableConfigOverride setIgnorals(JsonIgnoreProperties.Value v);
314
public MutableConfigOverride setSetterInfo(JsonSetter.Value v);
315
public MutableConfigOverride setVisibility(VisibilityChecker.Std v);
316
public MutableConfigOverride setMergeable(Boolean v);
317
public MutableConfigOverride setNullHandling(JsonSetter.Value v);
318
}
319
320
public class ConfigOverrides {
321
// Override access
322
public ConfigOverride findOverride(Class<?> type);
323
324
// Default settings
325
public MutableConfigOverride setDefaultInclusion(JsonInclude.Value v);
326
public MutableConfigOverride setDefaultSetterInfo(JsonSetter.Value v);
327
public MutableConfigOverride setDefaultMergeable(Boolean v);
328
public MutableConfigOverride setDefaultLeniency(Boolean v);
329
330
// Type-specific overrides
331
public MutableConfigOverride findOrCreateOverride(Class<?> type);
332
}
333
```
334
335
## Context Attributes
336
337
### ContextAttributes
338
339
ContextAttributes provides a way to pass context-specific data during serialization/deserialization.
340
341
```java { .api }
342
public abstract class ContextAttributes {
343
// Attribute access
344
public abstract Object getAttribute(Object key);
345
public abstract ContextAttributes withSharedAttribute(Object key, Object value);
346
public abstract ContextAttributes withSharedAttributes(Map<?, ?> attributes);
347
public abstract ContextAttributes withPerCallAttribute(Object key, Object value);
348
public abstract ContextAttributes withoutSharedAttribute(Object key);
349
350
// Factory methods
351
public static ContextAttributes getEmpty();
352
353
// Implementation class
354
public static class Impl extends ContextAttributes implements Serializable {
355
public Impl(Map<?, ?> shared);
356
public Impl(Map<?, ?> shared, Map<?, ?> perCall);
357
358
public Object getAttribute(Object key);
359
public ContextAttributes withSharedAttribute(Object key, Object value);
360
public ContextAttributes withSharedAttributes(Map<?, ?> attributes);
361
public ContextAttributes withPerCallAttribute(Object key, Object value);
362
public ContextAttributes withoutSharedAttribute(Object key);
363
}
364
}
365
```
366
367
## Constructor Detection
368
369
### ConstructorDetector
370
371
ConstructorDetector configures how constructors are detected and used for deserialization.
372
373
```java { .api }
374
public final class ConstructorDetector implements Serializable {
375
// Predefined strategies
376
public static final ConstructorDetector DEFAULT;
377
public static final ConstructorDetector USE_PROPERTIES_BASED;
378
public static final ConstructorDetector USE_DELEGATING;
379
public static final ConstructorDetector EXPLICIT_ONLY;
380
381
// Factory methods
382
public static ConstructorDetector requireCtorAnnotation();
383
public static ConstructorDetector useDefaultConstructor();
384
public static ConstructorDetector useDelegating();
385
public static ConstructorDetector useProperties();
386
387
// Configuration methods
388
public ConstructorDetector withRequireAnnotation(boolean state);
389
public ConstructorDetector withAllowJDKTypeConstructors(boolean state);
390
public ConstructorDetector withSingleArgConstructorStrategy(SingleArgConstructor strategy);
391
392
// Query methods
393
public boolean requireCtorAnnotation();
394
public boolean allowJDKTypeConstructors();
395
public SingleArgConstructor singleArgConstructorStrategy();
396
397
// Single argument constructor strategy
398
public enum SingleArgConstructor {
399
DELEGATING,
400
PROPERTIES,
401
HEURISTIC;
402
}
403
}
404
```
405
406
## Coercion Configuration
407
408
### CoercionConfig
409
410
CoercionConfig controls type coercion behavior during deserialization.
411
412
```java { .api }
413
public class CoercionConfig implements Serializable {
414
// Coercion action lookup
415
public CoercionAction findAction(CoercionInputShape inputShape);
416
417
// Boolean coercion settings
418
public Boolean getAcceptBlankAsEmpty();
419
420
// State checking
421
public boolean isCoercionEnabled();
422
}
423
424
public class MutableCoercionConfig extends CoercionConfig {
425
// Action configuration
426
public MutableCoercionConfig setCoercion(CoercionInputShape shape, CoercionAction action);
427
public MutableCoercionConfig setAcceptBlankAsEmpty(Boolean state);
428
}
429
430
public class CoercionConfigs implements Serializable {
431
// Default coercion lookup
432
public CoercionAction findCoercion(DeserializationConfig config, LogicalType logicalType, Class<?> rawTargetType, CoercionInputShape inputShape);
433
public CoercionAction findCoercionFromBlankString(DeserializationConfig config, LogicalType logicalType, Class<?> rawTargetType, CoercionAction actionIfBlankNotAllowed);
434
435
// Default coercion config access
436
public MutableCoercionConfig defaultCoercions();
437
438
// Type-specific coercion config
439
public MutableCoercionConfig findOrCreateCoercion(LogicalType logicalType);
440
public MutableCoercionConfig findOrCreateCoercion(Class<?> rawType);
441
}
442
443
// Coercion enums
444
public enum CoercionAction {
445
AsEmpty,
446
AsNull,
447
Fail,
448
TryConvert;
449
}
450
451
public enum CoercionInputShape {
452
Array,
453
Boolean,
454
Float,
455
Integer,
456
Object,
457
String;
458
}
459
```
460
461
## Cache Configuration
462
463
### CacheProvider
464
465
CacheProvider allows customization of caching strategies for deserializers, serializers, and type information.
466
467
```java { .api }
468
public interface CacheProvider {
469
// Cache creation for different components
470
LookupCache<Object, JsonDeserializer<Object>> forDeserializerCache(DeserializationConfig config);
471
LookupCache<Object, JsonSerializer<Object>> forSerializerCache(SerializationConfig config);
472
LookupCache<Object, JavaType> forTypeFactory();
473
}
474
475
public class DefaultCacheProvider implements CacheProvider {
476
// Default cache instances
477
public static final CacheProvider INSTANCE;
478
479
// Cache factory methods with default implementations
480
public LookupCache<Object, JsonDeserializer<Object>> forDeserializerCache(DeserializationConfig config);
481
public LookupCache<Object, JsonSerializer<Object>> forSerializerCache(SerializationConfig config);
482
public LookupCache<Object, JavaType> forTypeFactory();
483
}
484
```
485
486
## Usage Examples
487
488
### Basic Feature Configuration
489
490
```java
491
import com.fasterxml.jackson.databind.ObjectMapper;
492
import com.fasterxml.jackson.databind.SerializationFeature;
493
import com.fasterxml.jackson.databind.DeserializationFeature;
494
import com.fasterxml.jackson.databind.MapperFeature;
495
496
ObjectMapper mapper = new ObjectMapper();
497
498
// Configure serialization features
499
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
500
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
501
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
502
503
// Configure deserialization features
504
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
505
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
506
mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
507
508
// Configure mapper features
509
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
510
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
511
512
// Enable/disable multiple features at once
513
mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,
514
SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
515
516
mapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,
517
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
518
519
// Check feature status
520
boolean indented = mapper.isEnabled(SerializationFeature.INDENT_OUTPUT);
521
boolean caseSensitive = !mapper.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
522
boolean strict = mapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
523
```
524
525
### Configuration Overrides
526
527
```java
528
import com.fasterxml.jackson.annotation.JsonInclude;
529
import com.fasterxml.jackson.annotation.JsonFormat;
530
import com.fasterxml.jackson.databind.cfg.ConfigOverrides;
531
532
ObjectMapper mapper = new ObjectMapper();
533
534
// Global inclusion setting
535
mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
536
537
// Per-type overrides
538
ConfigOverrides overrides = mapper.getConfigOverrides();
539
540
// Override Date formatting for all Date fields
541
overrides.findOrCreateOverride(Date.class)
542
.setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd"));
543
544
// Override inclusion for specific type
545
overrides.findOrCreateOverride(OptionalData.class)
546
.setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, null));
547
548
// Override property naming for specific type
549
overrides.findOrCreateOverride(LegacyData.class)
550
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.OBJECT));
551
552
// Multiple overrides for a type
553
overrides.findOrCreateOverride(PersonData.class)
554
.setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_DEFAULT, null))
555
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.OBJECT))
556
.setMergeable(Boolean.TRUE);
557
```
558
559
### Context Attributes
560
561
```java
562
import com.fasterxml.jackson.databind.cfg.ContextAttributes;
563
564
ObjectMapper mapper = new ObjectMapper();
565
566
// Set default context attributes
567
Map<String, Object> defaultAttrs = new HashMap<>();
568
defaultAttrs.put("version", "2.0");
569
defaultAttrs.put("environment", "production");
570
mapper.setDefaultAttributes(ContextAttributes.getEmpty().withSharedAttributes(defaultAttrs));
571
572
// Use with ObjectReader/ObjectWriter for per-operation attributes
573
ObjectReader reader = mapper.reader()
574
.withAttribute("requestId", "12345")
575
.withAttribute("userId", "user123");
576
577
ObjectWriter writer = mapper.writer()
578
.withAttribute("outputFormat", "compact")
579
.withAttribute("includeMetadata", true);
580
581
// Custom serializer that uses context attributes
582
public class MetadataAwareSerializer extends StdSerializer<MyData> {
583
584
public MetadataAwareSerializer() {
585
super(MyData.class);
586
}
587
588
@Override
589
public void serialize(MyData value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
590
gen.writeStartObject();
591
592
// Write standard fields
593
gen.writeStringField("id", value.getId());
594
gen.writeStringField("name", value.getName());
595
596
// Check context for metadata inclusion
597
Boolean includeMetadata = (Boolean) serializers.getAttribute("includeMetadata");
598
if (Boolean.TRUE.equals(includeMetadata)) {
599
gen.writeStringField("version", (String) serializers.getAttribute("version"));
600
gen.writeStringField("environment", (String) serializers.getAttribute("environment"));
601
}
602
603
gen.writeEndObject();
604
}
605
}
606
```
607
608
### Constructor Detection Configuration
609
610
```java
611
import com.fasterxml.jackson.databind.cfg.ConstructorDetector;
612
613
ObjectMapper mapper = new ObjectMapper();
614
615
// Require explicit @JsonCreator annotations
616
mapper.setConstructorDetector(ConstructorDetector.requireCtorAnnotation());
617
618
// Use properties-based detection primarily
619
mapper.setConstructorDetector(ConstructorDetector.useProperties());
620
621
// Custom constructor detection strategy
622
ConstructorDetector customDetector = ConstructorDetector.DEFAULT
623
.withRequireAnnotation(false)
624
.withAllowJDKTypeConstructors(true)
625
.withSingleArgConstructorStrategy(ConstructorDetector.SingleArgConstructor.HEURISTIC);
626
627
mapper.setConstructorDetector(customDetector);
628
629
// Example POJOs that work with different strategies
630
public class ExplicitPerson {
631
private String name;
632
private int age;
633
634
// Requires @JsonCreator when using requireCtorAnnotation()
635
@JsonCreator
636
public ExplicitPerson(@JsonProperty("name") String name, @JsonProperty("age") int age) {
637
this.name = name;
638
this.age = age;
639
}
640
641
// getters/setters
642
}
643
644
public class PropertiesPerson {
645
private String name;
646
private int age;
647
648
// No annotations needed when using useProperties()
649
public PropertiesPerson(String name, int age) {
650
this.name = name;
651
this.age = age;
652
}
653
654
// getters/setters
655
}
656
```
657
658
### Coercion Configuration
659
660
```java
661
import com.fasterxml.jackson.databind.cfg.CoercionAction;
662
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
663
import com.fasterxml.jackson.databind.type.LogicalType;
664
665
ObjectMapper mapper = new ObjectMapper();
666
667
// Configure default coercion behavior
668
mapper.coercionConfigDefaults()
669
.setCoercion(CoercionInputShape.String, CoercionAction.TryConvert)
670
.setCoercion(CoercionInputShape.Integer, CoercionAction.TryConvert)
671
.setAcceptBlankAsEmpty(Boolean.TRUE);
672
673
// Configure coercion for specific logical types
674
mapper.coercionConfigFor(LogicalType.Boolean)
675
.setCoercion(CoercionInputShape.String, CoercionAction.TryConvert);
676
677
mapper.coercionConfigFor(LogicalType.Integer)
678
.setCoercion(CoercionInputShape.Float, CoercionAction.TryConvert)
679
.setCoercion(CoercionInputShape.String, CoercionAction.Fail);
680
681
// Configure coercion for specific Java types
682
mapper.coercionConfigFor(LocalDate.class)
683
.setCoercion(CoercionInputShape.String, CoercionAction.TryConvert)
684
.setAcceptBlankAsEmpty(Boolean.FALSE);
685
686
// Test coercion behavior
687
String json = """
688
{
689
"active": "true",
690
"count": "123",
691
"rate": 45.67,
692
"date": "2024-01-15"
693
}
694
""";
695
696
// This will succeed with coercion enabled
697
DataRecord record = mapper.readValue(json, DataRecord.class);
698
699
public class DataRecord {
700
public boolean active; // "true" -> true
701
public int count; // "123" -> 123
702
public int rate; // 45.67 -> 45 (if coercion enabled)
703
public LocalDate date; // "2024-01-15" -> LocalDate (if coercion enabled)
704
}
705
```
706
707
### Advanced Configuration with Builder
708
709
```java
710
import com.fasterxml.jackson.databind.json.JsonMapper;
711
712
// Using JsonMapper builder for comprehensive configuration
713
JsonMapper mapper = JsonMapper.builder()
714
// Features
715
.enable(SerializationFeature.INDENT_OUTPUT)
716
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
717
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
718
719
// Date handling
720
.defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
721
.defaultTimeZone(TimeZone.getTimeZone("UTC"))
722
.defaultLocale(Locale.US)
723
724
// Property inclusion
725
.serializationInclusion(JsonInclude.Include.NON_NULL)
726
727
// Property naming
728
.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
729
730
// Visibility
731
.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
732
.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
733
734
// Constructor detection
735
.constructorDetector(ConstructorDetector.useProperties())
736
737
// Polymorphic type validation
738
.polymorphicTypeValidator(BasicPolymorphicTypeValidator.builder()
739
.allowIfSubType("com.example.model")
740
.build())
741
742
// Build the mapper
743
.build();
744
745
// Additional configuration after building
746
mapper.registerModule(new JavaTimeModule());
747
mapper.addMixIn(ThirdPartyClass.class, ThirdPartyMixin.class);
748
749
// Type-specific overrides
750
mapper.configOverride(BigDecimal.class)
751
.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
752
```
753
754
### Custom Configuration Classes
755
756
```java
757
// Custom configuration holder
758
public class JsonConfiguration {
759
private final ObjectMapper mapper;
760
761
public JsonConfiguration() {
762
this.mapper = createConfiguredMapper();
763
}
764
765
private ObjectMapper createConfiguredMapper() {
766
ObjectMapper mapper = new ObjectMapper();
767
768
// Standard configuration
769
configureFeatures(mapper);
770
configureFormatting(mapper);
771
configureCoercion(mapper);
772
configureOverrides(mapper);
773
774
return mapper;
775
}
776
777
private void configureFeatures(ObjectMapper mapper) {
778
// Serialization
779
mapper.enable(SerializationFeature.INDENT_OUTPUT);
780
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
781
782
// Deserialization
783
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
784
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
785
786
// Mapper
787
mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
788
mapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
789
}
790
791
private void configureFormatting(ObjectMapper mapper) {
792
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
793
mapper.setTimeZone(TimeZone.getTimeZone("UTC"));
794
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE);
795
}
796
797
private void configureCoercion(ObjectMapper mapper) {
798
mapper.coercionConfigDefaults()
799
.setAcceptBlankAsEmpty(Boolean.TRUE);
800
801
mapper.coercionConfigFor(LogicalType.Boolean)
802
.setCoercion(CoercionInputShape.String, CoercionAction.TryConvert);
803
}
804
805
private void configureOverrides(ObjectMapper mapper) {
806
// Date formatting override
807
mapper.configOverride(Date.class)
808
.setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd"));
809
810
// Inclusion override for Optional types
811
mapper.configOverride(Optional.class)
812
.setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, null));
813
}
814
815
public ObjectMapper getMapper() {
816
return mapper;
817
}
818
819
// Environment-specific configurations
820
public static JsonConfiguration forProduction() {
821
JsonConfiguration config = new JsonConfiguration();
822
config.mapper.disable(SerializationFeature.INDENT_OUTPUT); // Compact output
823
config.mapper.enable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // Strict validation
824
return config;
825
}
826
827
public static JsonConfiguration forDevelopment() {
828
JsonConfiguration config = new JsonConfiguration();
829
config.mapper.enable(SerializationFeature.INDENT_OUTPUT); // Pretty printing
830
config.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // Lenient
831
return config;
832
}
833
}
834
```
835
836
## Types
837
838
```java { .api }
839
// Configuration feature interface
840
public interface ConfigFeature {
841
boolean enabledByDefault();
842
int getMask();
843
boolean enabledIn(int flags);
844
}
845
846
// Factory configuration classes
847
public final class SerializerFactoryConfig implements Serializable {
848
public SerializerFactoryConfig withAdditionalSerializers(Serializers additional);
849
public SerializerFactoryConfig withAdditionalKeySerializers(Serializers additional);
850
public SerializerFactoryConfig withSerializerModifier(BeanSerializerModifier modifier);
851
public SerializerFactoryConfig withFilters(FilterProvider filterProvider);
852
public boolean hasSerializers();
853
public boolean hasKeySerializers();
854
public boolean hasSerializerModifiers();
855
public Iterable<Serializers> serializers();
856
public Iterable<Serializers> keySerializers();
857
public Iterable<BeanSerializerModifier> serializerModifiers();
858
public FilterProvider filterProvider();
859
}
860
861
public class DeserializerFactoryConfig implements Serializable {
862
public DeserializerFactoryConfig withAdditionalDeserializers(Deserializers additional);
863
public DeserializerFactoryConfig withAdditionalKeyDeserializers(KeyDeserializers additional);
864
public DeserializerFactoryConfig withDeserializerModifier(BeanDeserializerModifier modifier);
865
public DeserializerFactoryConfig withAbstractTypeResolver(AbstractTypeResolver resolver);
866
public DeserializerFactoryConfig withValueInstantiators(ValueInstantiators instantiators);
867
public boolean hasDeserializers();
868
public boolean hasKeyDeserializers();
869
public boolean hasDeserializerModifiers();
870
public boolean hasAbstractTypeResolvers();
871
public boolean hasValueInstantiators();
872
public Iterable<Deserializers> deserializers();
873
public Iterable<KeyDeserializers> keyDeserializers();
874
public Iterable<BeanDeserializerModifier> deserializerModifiers();
875
public Iterable<AbstractTypeResolver> abstractTypeResolvers();
876
public Iterable<ValueInstantiators> valueInstantiators();
877
}
878
879
// Datatype feature interface for specialized features
880
public interface DatatypeFeature extends JacksonFeature {
881
boolean enabledByDefault();
882
int getMask();
883
boolean enabledIn(int flags);
884
}
885
886
// Container for datatype features
887
public class DatatypeFeatures {
888
public static DatatypeFeatures defaultFeatures();
889
public boolean isEnabled(DatatypeFeature feature);
890
public DatatypeFeatures with(DatatypeFeature feature);
891
public DatatypeFeatures without(DatatypeFeature feature);
892
public DatatypeFeatures withFeatures(DatatypeFeature... features);
893
public DatatypeFeatures withoutFeatures(DatatypeFeature... features);
894
}
895
896
// Enum and JsonNode features
897
public enum EnumFeature implements DatatypeFeature {
898
READ_ENUM_KEYS_USING_INDEX(false),
899
WRITE_ENUM_KEYS_USING_INDEX(false);
900
}
901
902
public enum JsonNodeFeature implements DatatypeFeature {
903
READ_NULL_PROPERTIES(false),
904
WRITE_NULL_PROPERTIES(true);
905
}
906
```