0
# JSON Processing Configuration
1
2
Spring Boot's JSON processing configuration provides comprehensive auto-configuration for popular JSON libraries including Jackson, Gson, and JSON-B.
3
4
## Capabilities
5
6
### Jackson Configuration
7
8
Auto-configuration for Jackson JSON processing with comprehensive serialization and deserialization options.
9
10
```java { .api }
11
/**
12
* Auto-configuration for Jackson JSON processing
13
* Configures ObjectMapper with sensible defaults and customization options
14
*/
15
@AutoConfiguration
16
@ConditionalOnClass(ObjectMapper.class)
17
public class JacksonAutoConfiguration {
18
19
/**
20
* Jackson ObjectMapper for JSON processing
21
*/
22
@Bean
23
@Primary
24
@ConditionalOnMissingBean
25
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperFactory factory) {
26
return factory.createObjectMapper();
27
}
28
29
/**
30
* Jackson ObjectMapper builder for customization
31
*/
32
@Bean
33
@ConditionalOnMissingBean
34
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(
35
ApplicationContext applicationContext,
36
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
37
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
38
builder.applicationContext(applicationContext);
39
customize(builder, customizers);
40
return builder;
41
}
42
}
43
44
/**
45
* Jackson configuration properties
46
*/
47
@ConfigurationProperties(prefix = "spring.jackson")
48
public class JacksonProperties {
49
50
/**
51
* Date format string or a fully-qualified date format class name
52
*/
53
private String dateFormat;
54
55
/**
56
* Jackson on/off features that affect the way Java objects are serialized
57
*/
58
private final Map<SerializationFeature, Boolean> serialization = new EnumMap<>(SerializationFeature.class);
59
60
/**
61
* Jackson on/off features that affect the way Java objects are deserialized
62
*/
63
private final Map<DeserializationFeature, Boolean> deserialization = new EnumMap<>(DeserializationFeature.class);
64
65
/**
66
* Jackson general purpose on/off features
67
*/
68
private final Map<MapperFeature, Boolean> mapper = new EnumMap<>(MapperFeature.class);
69
70
/**
71
* Jackson on/off features for parsers
72
*/
73
private final Map<JsonParser.Feature, Boolean> parser = new EnumMap<>(JsonParser.Feature.class);
74
75
/**
76
* Jackson on/off features for generators
77
*/
78
private final Map<JsonGenerator.Feature, Boolean> generator = new EnumMap<>(JsonGenerator.Feature.class);
79
80
/**
81
* Controls the inclusion of properties during serialization
82
*/
83
private JsonInclude.Include defaultPropertyInclusion;
84
85
/**
86
* Time zone used when formatting dates
87
*/
88
private TimeZone timeZone;
89
90
/**
91
* Locale used for formatting
92
*/
93
private Locale locale;
94
95
/**
96
* Property naming strategy
97
*/
98
private String propertyNamingStrategy;
99
100
/**
101
* Global visibility thresholds for auto-detection
102
*/
103
private final Visibility visibility = new Visibility();
104
105
// Getters and setters
106
public String getDateFormat() { return this.dateFormat; }
107
public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; }
108
public Map<SerializationFeature, Boolean> getSerialization() { return this.serialization; }
109
public Map<DeserializationFeature, Boolean> getDeserialization() { return this.deserialization; }
110
public JsonInclude.Include getDefaultPropertyInclusion() { return this.defaultPropertyInclusion; }
111
public void setDefaultPropertyInclusion(JsonInclude.Include defaultPropertyInclusion) {
112
this.defaultPropertyInclusion = defaultPropertyInclusion;
113
}
114
115
/**
116
* Jackson visibility configuration
117
*/
118
public static class Visibility {
119
/**
120
* Visibility threshold for auto-detecting fields
121
*/
122
private JsonAutoDetect.Visibility field;
123
124
/**
125
* Visibility threshold for auto-detecting getters
126
*/
127
private JsonAutoDetect.Visibility getter;
128
129
/**
130
* Visibility threshold for auto-detecting setters
131
*/
132
private JsonAutoDetect.Visibility setter;
133
134
/**
135
* Visibility threshold for auto-detecting creators
136
*/
137
private JsonAutoDetect.Visibility creator;
138
139
/**
140
* Visibility threshold for auto-detecting is-getters
141
*/
142
private JsonAutoDetect.Visibility isGetter;
143
144
// Getters and setters
145
public JsonAutoDetect.Visibility getField() { return this.field; }
146
public void setField(JsonAutoDetect.Visibility field) { this.field = field; }
147
public JsonAutoDetect.Visibility getGetter() { return this.getter; }
148
public void setGetter(JsonAutoDetect.Visibility getter) { this.getter = getter; }
149
}
150
}
151
```
152
153
### Gson Configuration
154
155
Auto-configuration for Google Gson JSON processing library.
156
157
```java { .api }
158
/**
159
* Auto-configuration for Google Gson
160
* Configures Gson with customization options for JSON processing
161
*/
162
@AutoConfiguration
163
@ConditionalOnClass(Gson.class)
164
@ConditionalOnMissingClass("com.fasterxml.jackson.databind.ObjectMapper")
165
public class GsonAutoConfiguration {
166
167
/**
168
* Gson instance for JSON processing
169
*/
170
@Bean
171
@ConditionalOnMissingBean
172
public Gson gson(GsonProperties properties, List<GsonBuilderCustomizer> customizers) {
173
GsonBuilder builder = new GsonBuilder();
174
175
if (properties.isGenerateNonExecutableJson()) {
176
builder.generateNonExecutableJson();
177
}
178
if (properties.isExcludeFieldsWithoutExposeAnnotation()) {
179
builder.excludeFieldsWithoutExposeAnnotation();
180
}
181
if (properties.isSerializeNulls()) {
182
builder.serializeNulls();
183
}
184
if (properties.isEnableComplexMapKeySerialization()) {
185
builder.enableComplexMapKeySerialization();
186
}
187
if (properties.isDisableInnerClassSerialization()) {
188
builder.disableInnerClassSerialization();
189
}
190
191
Long version = properties.getVersion();
192
if (version != null) {
193
builder.setVersion(version);
194
}
195
196
if (properties.getLenient() != null && properties.getLenient()) {
197
builder.setLenient();
198
}
199
200
if (properties.getDisableHtmlEscaping() != null && properties.getDisableHtmlEscaping()) {
201
builder.disableHtmlEscaping();
202
}
203
204
String dateFormat = properties.getDateFormat();
205
if (dateFormat != null) {
206
builder.setDateFormat(dateFormat);
207
}
208
209
customizers.forEach(customizer -> customizer.customize(builder));
210
return builder.create();
211
}
212
}
213
214
/**
215
* Gson configuration properties
216
*/
217
@ConfigurationProperties(prefix = "spring.gson")
218
public class GsonProperties {
219
220
/**
221
* Whether to generate non-executable JSON by prefixing the output with some special text
222
*/
223
private Boolean generateNonExecutableJson;
224
225
/**
226
* Whether to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation
227
*/
228
private Boolean excludeFieldsWithoutExposeAnnotation;
229
230
/**
231
* Whether to serialize null fields
232
*/
233
private Boolean serializeNulls;
234
235
/**
236
* Whether to enable serialization of complex map keys (non-primitives)
237
*/
238
private Boolean enableComplexMapKeySerialization;
239
240
/**
241
* Whether to exclude inner classes during serialization
242
*/
243
private Boolean disableInnerClassSerialization;
244
245
/**
246
* Version number to use to ignore fields and objects
247
*/
248
private Long version;
249
250
/**
251
* Whether the parser should be lenient
252
*/
253
private Boolean lenient;
254
255
/**
256
* Whether to disable HTML escaping of characters
257
*/
258
private Boolean disableHtmlEscaping;
259
260
/**
261
* Format to use when serializing Date objects
262
*/
263
private String dateFormat;
264
265
/**
266
* Naming policy that should be applied to an object's field during serialization and deserialization
267
*/
268
private FieldNamingPolicy fieldNamingPolicy;
269
270
/**
271
* Serialization policy for Long and long types
272
*/
273
private LongSerializationPolicy longSerializationPolicy;
274
275
/**
276
* Precision for Double serialization
277
*/
278
private String prettyPrinting;
279
280
// Getters and setters
281
public Boolean getGenerateNonExecutableJson() { return this.generateNonExecutableJson; }
282
public void setGenerateNonExecutableJson(Boolean generateNonExecutableJson) {
283
this.generateNonExecutableJson = generateNonExecutableJson;
284
}
285
public Boolean getSerializeNulls() { return this.serializeNulls; }
286
public void setSerializeNulls(Boolean serializeNulls) { this.serializeNulls = serializeNulls; }
287
public String getDateFormat() { return this.dateFormat; }
288
public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; }
289
}
290
```
291
292
### JSON-B Configuration
293
294
Auto-configuration for JSON-B (JSON Binding) standard implementation.
295
296
```java { .api }
297
/**
298
* Auto-configuration for JSON-B (JSON Binding)
299
* Configures JSON-B for Java EE/Jakarta EE standard JSON processing
300
*/
301
@AutoConfiguration
302
@ConditionalOnClass({Jsonb.class, JsonbBuilder.class})
303
@ConditionalOnMissingClass({
304
"com.fasterxml.jackson.databind.ObjectMapper",
305
"com.google.gson.Gson"
306
})
307
public class JsonbAutoConfiguration {
308
309
/**
310
* JSON-B instance for JSON processing
311
*/
312
@Bean
313
@ConditionalOnMissingBean
314
public Jsonb jsonb(JsonbProperties properties, List<JsonbBuilderCustomizer> customizers) {
315
JsonbBuilder builder = JsonbBuilder.create();
316
317
JsonbConfig config = new JsonbConfig();
318
319
String dateFormat = properties.getDateFormat();
320
if (dateFormat != null) {
321
config.withDateFormat(dateFormat, null);
322
}
323
324
Locale locale = properties.getLocale();
325
if (locale != null) {
326
config.withLocale(locale);
327
}
328
329
Boolean nullValues = properties.getNullValues();
330
if (nullValues != null) {
331
if (nullValues) {
332
config.withNullValues(true);
333
}
334
}
335
336
Boolean prettyPrinting = properties.getPrettyPrinting();
337
if (prettyPrinting != null && prettyPrinting) {
338
config.withFormatting(true);
339
}
340
341
PropertyNamingStrategy namingStrategy = properties.getNamingStrategy();
342
if (namingStrategy != null) {
343
config.withPropertyNamingStrategy(namingStrategy);
344
}
345
346
customizers.forEach(customizer -> customizer.customize(builder));
347
return builder.withConfig(config).build();
348
}
349
}
350
351
/**
352
* JSON-B configuration properties
353
*/
354
@ConfigurationProperties(prefix = "spring.jsonb")
355
public class JsonbProperties {
356
357
/**
358
* Format string for date serialization
359
*/
360
private String dateFormat;
361
362
/**
363
* Locale for number and date formatting
364
*/
365
private Locale locale;
366
367
/**
368
* Whether to serialize properties with null values
369
*/
370
private Boolean nullValues;
371
372
/**
373
* Whether to format the output JSON with indentation
374
*/
375
private Boolean prettyPrinting;
376
377
/**
378
* Property naming strategy
379
*/
380
private PropertyNamingStrategy namingStrategy;
381
382
/**
383
* Encoding for JSON processing
384
*/
385
private String encoding = "UTF-8";
386
387
/**
388
* Whether to use strict mode for JSON processing
389
*/
390
private Boolean strict;
391
392
// Getters and setters
393
public String getDateFormat() { return this.dateFormat; }
394
public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; }
395
public Locale getLocale() { return this.locale; }
396
public void setLocale(Locale locale) { this.locale = locale; }
397
public Boolean getNullValues() { return this.nullValues; }
398
public void setNullValues(Boolean nullValues) { this.nullValues = nullValues; }
399
public Boolean getPrettyPrinting() { return this.prettyPrinting; }
400
public void setPrettyPrinting(Boolean prettyPrinting) { this.prettyPrinting = prettyPrinting; }
401
public PropertyNamingStrategy getNamingStrategy() { return this.namingStrategy; }
402
public void setNamingStrategy(PropertyNamingStrategy namingStrategy) { this.namingStrategy = namingStrategy; }
403
}
404
```
405
406
**Usage Examples:**
407
408
```java
409
// Jackson usage
410
@RestController
411
public class UserController {
412
413
private final ObjectMapper objectMapper;
414
415
public UserController(ObjectMapper objectMapper) {
416
this.objectMapper = objectMapper;
417
}
418
419
@PostMapping("/api/users")
420
public ResponseEntity<User> createUser(@RequestBody CreateUserRequest request) throws JsonProcessingException {
421
// Jackson automatically deserializes JSON request body
422
User user = userService.createUser(request);
423
424
// Manual JSON processing if needed
425
String userJson = objectMapper.writeValueAsString(user);
426
User parsedUser = objectMapper.readValue(userJson, User.class);
427
428
return ResponseEntity.ok(user); // Jackson automatically serializes response
429
}
430
}
431
432
// Custom Jackson configuration
433
@Configuration
434
public class JacksonConfig {
435
436
@Bean
437
@Primary
438
public ObjectMapper objectMapper() {
439
return Jackson2ObjectMapperBuilder.json()
440
.dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
441
.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
442
.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
443
.featuresToEnable(SerializationFeature.INDENT_OUTPUT)
444
.build();
445
}
446
447
@Bean
448
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
449
return builder -> {
450
builder.simpleDateFormat("yyyy-MM-dd");
451
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
452
};
453
}
454
}
455
456
// Gson usage
457
@Service
458
public class JsonProcessingService {
459
460
private final Gson gson;
461
462
public JsonProcessingService(Gson gson) {
463
this.gson = gson;
464
}
465
466
public String serializeToJson(Object object) {
467
return gson.toJson(object);
468
}
469
470
public <T> T deserializeFromJson(String json, Class<T> clazz) {
471
return gson.fromJson(json, clazz);
472
}
473
474
public <T> T deserializeFromJson(String json, Type type) {
475
return gson.fromJson(json, type);
476
}
477
}
478
479
// Custom Gson configuration
480
@Configuration
481
public class GsonConfig {
482
483
@Bean
484
public GsonBuilderCustomizer gsonBuilderCustomizer() {
485
return builder -> {
486
builder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter());
487
builder.registerTypeAdapter(BigDecimal.class, new BigDecimalAdapter());
488
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
489
};
490
}
491
}
492
493
// JSON-B usage
494
@Component
495
public class ReportGenerator {
496
497
private final Jsonb jsonb;
498
499
public ReportGenerator(Jsonb jsonb) {
500
this.jsonb = jsonb;
501
}
502
503
public String generateReportJson(Report report) {
504
return jsonb.toJson(report);
505
}
506
507
public Report parseReportJson(String json) {
508
return jsonb.fromJson(json, Report.class);
509
}
510
}
511
512
// Properties configuration
513
# application.properties
514
# Jackson
515
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
516
spring.jackson.time-zone=UTC
517
spring.jackson.property-naming-strategy=SNAKE_CASE
518
spring.jackson.default-property-inclusion=NON_NULL
519
spring.jackson.serialization.indent-output=true
520
spring.jackson.deserialization.fail-on-unknown-properties=false
521
522
# Gson
523
spring.gson.date-format=yyyy-MM-dd HH:mm:ss
524
spring.gson.serialize-nulls=false
525
spring.gson.pretty-printing=true
526
spring.gson.disable-html-escaping=true
527
spring.gson.lenient=true
528
529
# JSON-B
530
spring.jsonb.date-format=yyyy-MM-dd HH:mm:ss
531
spring.jsonb.locale=en_US
532
spring.jsonb.null-values=false
533
spring.jsonb.pretty-printing=true
534
spring.jsonb.naming-strategy=LOWER_CASE_WITH_UNDERSCORES
535
```
536
537
## Types
538
539
### JSON Configuration Types
540
541
```java { .api }
542
/**
543
* Customizer for Jackson ObjectMapper builder
544
*/
545
@FunctionalInterface
546
public interface Jackson2ObjectMapperBuilderCustomizer {
547
/**
548
* Customize the Jackson ObjectMapper builder
549
* @param jacksonObjectMapperBuilder the builder to customize
550
*/
551
void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder);
552
}
553
554
/**
555
* Customizer for Gson builder
556
*/
557
@FunctionalInterface
558
public interface GsonBuilderCustomizer {
559
/**
560
* Customize the Gson builder
561
* @param gsonBuilder the builder to customize
562
*/
563
void customize(GsonBuilder gsonBuilder);
564
}
565
566
/**
567
* Customizer for JSON-B builder
568
*/
569
@FunctionalInterface
570
public interface JsonbBuilderCustomizer {
571
/**
572
* Customize the JSON-B builder
573
* @param jsonbBuilder the builder to customize
574
*/
575
void customize(JsonbBuilder jsonbBuilder);
576
}
577
578
/**
579
* JSON serializer interface
580
*/
581
public interface JsonSerializer<T> {
582
/**
583
* Serialize object to JSON
584
* @param src the object to serialize
585
* @param typeOfSrc the type of the object
586
* @param context the serialization context
587
* @return JsonElement representation
588
*/
589
JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
590
}
591
592
/**
593
* JSON deserializer interface
594
*/
595
public interface JsonDeserializer<T> {
596
/**
597
* Deserialize JSON to object
598
* @param json the JSON element to deserialize
599
* @param typeOfT the type of the object
600
* @param context the deserialization context
601
* @return deserialized object
602
*/
603
T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException;
604
}
605
```