0
# Configuration
1
2
Gson provides extensive configuration options through the GsonBuilder class for customizing serialization and deserialization behavior.
3
4
## GsonBuilder
5
6
Builder pattern class for configuring Gson instances.
7
8
```java { .api }
9
public final class GsonBuilder {
10
public GsonBuilder();
11
12
// JSON formatting
13
public GsonBuilder setPrettyPrinting();
14
public GsonBuilder setFormattingStyle(FormattingStyle formattingStyle);
15
public GsonBuilder disableHtmlEscaping();
16
17
// Null handling
18
public GsonBuilder serializeNulls();
19
20
// Field naming
21
public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention);
22
public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy);
23
24
// Version control
25
public GsonBuilder setVersion(double version);
26
27
// Field exposure
28
public GsonBuilder excludeFieldsWithoutExposeAnnotation();
29
public GsonBuilder excludeFieldsWithModifiers(int... modifiers);
30
31
// Exclusion strategies
32
public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies);
33
public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy);
34
public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy);
35
36
// Type adapters
37
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter);
38
public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory);
39
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter);
40
41
// Number handling
42
public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy);
43
public GsonBuilder setObjectToNumberStrategy(ToNumberStrategy objectToNumberStrategy);
44
public GsonBuilder setNumberToNumberStrategy(ToNumberStrategy numberToNumberStrategy);
45
public GsonBuilder serializeSpecialFloatingPointValues();
46
47
// Date formatting
48
public GsonBuilder setDateFormat(String pattern);
49
public GsonBuilder setDateFormat(int dateStyle);
50
public GsonBuilder setDateFormat(int dateStyle, int timeStyle);
51
52
// JSON parsing strictness
53
public GsonBuilder setLenient();
54
public GsonBuilder setStrictness(Strictness strictness);
55
56
// Advanced options
57
public GsonBuilder enableComplexMapKeySerialization();
58
public GsonBuilder disableInnerClassSerialization();
59
public GsonBuilder generateNonExecutableJson();
60
public GsonBuilder disableJdkUnsafe();
61
public GsonBuilder addReflectionAccessFilter(ReflectionAccessFilter filter);
62
63
// Build final instance
64
public Gson create();
65
}
66
```
67
68
## Basic Configuration
69
70
**Creating a configured Gson instance:**
71
```java
72
Gson gson = new GsonBuilder()
73
.setPrettyPrinting()
74
.serializeNulls()
75
.create();
76
```
77
78
## Field Naming Policies
79
80
Control how Java field names are converted to JSON property names.
81
82
```java { .api }
83
public enum FieldNamingPolicy implements FieldNamingStrategy {
84
IDENTITY,
85
UPPER_CAMEL_CASE,
86
UPPER_CAMEL_CASE_WITH_SPACES,
87
UPPER_CASE_WITH_UNDERSCORES,
88
LOWER_CASE_WITH_UNDERSCORES,
89
LOWER_CASE_WITH_DASHES,
90
LOWER_CASE_WITH_DOTS
91
}
92
```
93
94
**Usage:**
95
```java
96
Gson gson = new GsonBuilder()
97
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
98
.create();
99
100
class Person {
101
String firstName; // becomes "first_name" in JSON
102
String lastName; // becomes "last_name" in JSON
103
}
104
```
105
106
## Custom Field Naming Strategy
107
108
```java { .api }
109
public interface FieldNamingStrategy {
110
public String translateName(Field f);
111
}
112
```
113
114
**Usage:**
115
```java
116
FieldNamingStrategy customStrategy = field -> {
117
return "prefix_" + field.getName().toLowerCase();
118
};
119
120
Gson gson = new GsonBuilder()
121
.setFieldNamingStrategy(customStrategy)
122
.create();
123
```
124
125
## Exclusion Strategies
126
127
Control which fields and classes are included in serialization/deserialization.
128
129
```java { .api }
130
public interface ExclusionStrategy {
131
public boolean shouldSkipField(FieldAttributes f);
132
public boolean shouldSkipClass(Class<?> clazz);
133
}
134
```
135
136
**Usage:**
137
```java
138
ExclusionStrategy strategy = new ExclusionStrategy() {
139
@Override
140
public boolean shouldSkipField(FieldAttributes f) {
141
return f.getName().startsWith("internal");
142
}
143
144
@Override
145
public boolean shouldSkipClass(Class<?> clazz) {
146
return clazz.getName().contains("Internal");
147
}
148
};
149
150
Gson gson = new GsonBuilder()
151
.setExclusionStrategies(strategy)
152
.create();
153
```
154
155
## Field Attributes
156
157
Information about fields for exclusion strategies.
158
159
```java { .api }
160
public final class FieldAttributes {
161
public Class<?> getDeclaringClass();
162
public String getName();
163
public Type getDeclaredType();
164
public Class<?> getDeclaredClass();
165
public <T extends Annotation> T getAnnotation(Class<T> annotation);
166
public Collection<Annotation> getAnnotations();
167
public boolean hasModifier(int modifier);
168
}
169
```
170
171
## Number Handling
172
173
### Long Serialization Policy
174
175
```java { .api }
176
public enum LongSerializationPolicy {
177
DEFAULT, // Serialize as numbers
178
STRING // Serialize as strings
179
}
180
```
181
182
**Usage:**
183
```java
184
Gson gson = new GsonBuilder()
185
.setLongSerializationPolicy(LongSerializationPolicy.STRING)
186
.create();
187
```
188
189
### Number Strategies
190
191
```java { .api }
192
public interface ToNumberStrategy {
193
public Number readNumber(JsonReader in) throws IOException;
194
}
195
196
public enum ToNumberPolicy implements ToNumberStrategy {
197
DOUBLE,
198
LAZILY_PARSED_NUMBER,
199
LONG_OR_DOUBLE,
200
BIG_DECIMAL
201
}
202
```
203
204
**Usage:**
205
```java
206
Gson gson = new GsonBuilder()
207
.setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
208
.setNumberToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
209
.create();
210
```
211
212
## Date Formatting
213
214
**Pattern-based formatting:**
215
```java
216
Gson gson = new GsonBuilder()
217
.setDateFormat("yyyy-MM-dd HH:mm:ss")
218
.create();
219
```
220
221
**Style-based formatting:**
222
```java
223
import java.text.DateFormat;
224
225
Gson gson = new GsonBuilder()
226
.setDateFormat(DateFormat.LONG)
227
.create();
228
229
// Or with both date and time styles
230
Gson gson = new GsonBuilder()
231
.setDateFormat(DateFormat.MEDIUM, DateFormat.SHORT)
232
.create();
233
```
234
235
## JSON Formatting
236
237
### Pretty Printing
238
239
```java
240
Gson gson = new GsonBuilder()
241
.setPrettyPrinting()
242
.create();
243
```
244
245
### Custom Formatting Style
246
247
```java { .api }
248
public class FormattingStyle {
249
public static FormattingStyle COMPACT;
250
public static FormattingStyle PRETTY;
251
252
public FormattingStyle withNewline(String newline);
253
public FormattingStyle withIndent(String indent);
254
public FormattingStyle withSpaceAfterSeparators(boolean spaceAfterSeparators);
255
}
256
```
257
258
**Usage:**
259
```java
260
FormattingStyle style = FormattingStyle.PRETTY
261
.withIndent(" ") // 4 spaces
262
.withNewline("\n");
263
264
Gson gson = new GsonBuilder()
265
.setFormattingStyle(style)
266
.create();
267
```
268
269
## Strictness Control
270
271
```java { .api }
272
public enum Strictness {
273
LENIENT, // Allows malformed JSON
274
STRICT // Requires well-formed JSON
275
}
276
```
277
278
**Usage:**
279
```java
280
// Lenient parsing (allows single quotes, unquoted names, etc.)
281
Gson gson = new GsonBuilder()
282
.setLenient()
283
.create();
284
285
// Or explicitly set strictness
286
Gson gson = new GsonBuilder()
287
.setStrictness(Strictness.LENIENT)
288
.create();
289
```
290
291
## Advanced Configuration
292
293
### Complex Map Keys
294
295
Enable serialization of complex objects as map keys:
296
```java
297
Gson gson = new GsonBuilder()
298
.enableComplexMapKeySerialization()
299
.create();
300
```
301
302
### HTML Escaping
303
304
Disable HTML character escaping:
305
```java
306
Gson gson = new GsonBuilder()
307
.disableHtmlEscaping()
308
.create();
309
```
310
311
### Reflection Access Control
312
313
```java { .api }
314
public interface ReflectionAccessFilter {
315
enum FilterResult { ALLOW, BLOCK_INACCESSIBLE, BLOCK_ALL }
316
317
FilterResult check(Class<?> rawClass);
318
}
319
```
320
321
**Usage:**
322
```java
323
ReflectionAccessFilter filter = new ReflectionAccessFilter() {
324
@Override
325
public FilterResult check(Class<?> rawClass) {
326
if (rawClass.getPackage().getName().startsWith("com.example.internal")) {
327
return FilterResult.BLOCK_ALL;
328
}
329
return FilterResult.ALLOW;
330
}
331
};
332
333
Gson gson = new GsonBuilder()
334
.addReflectionAccessFilter(filter)
335
.create();
336
```
337
338
### Version Control
339
340
Use `@Since` and `@Until` annotations with version setting:
341
```java
342
Gson gson = new GsonBuilder()
343
.setVersion(2.0)
344
.create();
345
```
346
347
### Modifier-based Exclusion
348
349
Exclude fields based on Java modifiers:
350
```java
351
import java.lang.reflect.Modifier;
352
353
Gson gson = new GsonBuilder()
354
.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT)
355
.create();
356
```