0
# Annotations and Configuration
1
2
Comprehensive annotation system for customizing JSON serialization and deserialization behavior at class and field levels. Provides fine-grained control over naming strategies, field inclusion, custom serializers, and more.
3
4
## Capabilities
5
6
### Field-Level Customization
7
8
Control individual field serialization and deserialization behavior with @JSONField annotation.
9
10
```java { .api }
11
/**
12
* Field-level customization annotation
13
*/
14
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
15
@Retention(RetentionPolicy.RUNTIME)
16
public @interface JSONField {
17
18
/**
19
* Custom field name in JSON
20
* @return Custom name or empty for default
21
*/
22
String name() default "";
23
24
/**
25
* Field ordering for serialization
26
* @return Order value (lower values first)
27
*/
28
int ordinal() default 0;
29
30
/**
31
* Date format pattern for Date/LocalDateTime fields
32
* @return Format pattern (e.g., "yyyy-MM-dd HH:mm:ss")
33
*/
34
String format() default "";
35
36
/**
37
* Whether to include field in serialization
38
* @return true to serialize, false to skip
39
*/
40
boolean serialize() default true;
41
42
/**
43
* Whether to include field in deserialization
44
* @return true to deserialize, false to skip
45
*/
46
boolean deserialize() default true;
47
48
/**
49
* Alternative names for deserialization
50
* @return Array of alternative field names
51
*/
52
String[] alternateNames() default {};
53
54
/**
55
* Custom serializer class
56
* @return ObjectWriter class for custom serialization
57
*/
58
Class<? extends ObjectWriter<?>> serializeUsing() default Void.class;
59
60
/**
61
* Custom deserializer class
62
* @return ObjectReader class for custom deserialization
63
*/
64
Class<? extends ObjectReader<?>> deserializeUsing() default Void.class;
65
66
/**
67
* Mark field as required during deserialization
68
* @return true if field must be present
69
*/
70
boolean required() default false;
71
72
/**
73
* Unwrap nested object fields to parent level
74
* @return true to flatten nested object
75
*/
76
boolean unwrapped() default false;
77
}
78
```
79
80
### Class-Level Configuration
81
82
Configure entire classes with @JSONType annotation for global serialization behavior.
83
84
```java { .api }
85
/**
86
* Class-level configuration annotation
87
*/
88
@Target({ElementType.TYPE})
89
@Retention(RetentionPolicy.RUNTIME)
90
public @interface JSONType {
91
92
/**
93
* Property naming strategy
94
* @return Naming strategy enum
95
*/
96
PropertyNamingStrategy naming() default PropertyNamingStrategy.CamelCase;
97
98
/**
99
* Field ordering for serialization
100
* @return Array of field names in desired order
101
*/
102
String[] orders() default {};
103
104
/**
105
* Fields to include in serialization
106
* @return Array of field names to include
107
*/
108
String[] includes() default {};
109
110
/**
111
* Fields to ignore in serialization
112
* @return Array of field names to ignore
113
*/
114
String[] ignores() default {};
115
116
/**
117
* Polymorphic type handling
118
* @return Array of subclasses for type resolution
119
*/
120
Class<?>[] seeAlso() default {};
121
122
/**
123
* Custom serializer for this class
124
* @return ObjectWriter class for custom serialization
125
*/
126
Class<? extends ObjectWriter<?>> serializer() default Void.class;
127
128
/**
129
* Custom deserializer for this class
130
* @return ObjectReader class for custom deserialization
131
*/
132
Class<? extends ObjectReader<?>> deserializer() default Void.class;
133
134
/**
135
* Serialization filters to apply
136
* @return Array of filter classes
137
*/
138
Class<? extends Filter>[] serializeFilters() default {};
139
}
140
```
141
142
### Constructor and Builder Support
143
144
Mark constructors and builder methods for object creation during deserialization.
145
146
```java { .api }
147
/**
148
* Mark constructor or static method for deserialization
149
*/
150
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
151
@Retention(RetentionPolicy.RUNTIME)
152
public @interface JSONCreator {
153
}
154
155
/**
156
* Enable builder pattern support
157
*/
158
@Target({ElementType.TYPE})
159
@Retention(RetentionPolicy.RUNTIME)
160
public @interface JSONBuilder {
161
162
/**
163
* Builder class to use
164
* @return Builder class
165
*/
166
Class<?> builderClass() default Void.class;
167
168
/**
169
* Method name to create builder instance
170
* @return Static method name (default: "builder")
171
*/
172
String builderMethodName() default "builder";
173
174
/**
175
* Method name to build final object
176
* @return Instance method name (default: "build")
177
*/
178
String buildMethodName() default "build";
179
}
180
```
181
182
### Performance Optimization
183
184
Enable compilation optimizations for frequently used classes.
185
186
```java { .api }
187
/**
188
* Enable compilation optimizations
189
*/
190
@Target({ElementType.TYPE})
191
@Retention(RetentionPolicy.RUNTIME)
192
public @interface JSONCompiled {
193
}
194
```
195
196
### Property Naming Strategies
197
198
Enumeration of available naming strategies for automatic property name transformation.
199
200
```java { .api }
201
/**
202
* Property naming strategies
203
*/
204
public enum PropertyNamingStrategy {
205
/** Keep original Java naming (default) */
206
CamelCase,
207
208
/** Capitalize first letter */
209
PascalCase,
210
211
/** Use underscores between words */
212
SnakeCase,
213
214
/** Convert to uppercase */
215
UpperCase,
216
217
/** Pascal case with spaces */
218
UpperCamelCaseWithSpaces,
219
220
/** Pascal case with underscores */
221
UpperCamelCaseWithUnderScores,
222
223
/** Pascal case with dashes */
224
UpperCamelCaseWithDashes
225
}
226
```
227
228
**Usage Examples:**
229
230
```java
231
import com.alibaba.fastjson2.annotation.*;
232
233
// Field-level customization
234
public class User {
235
@JSONField(name = "user_id", ordinal = 1)
236
private Long id;
237
238
@JSONField(ordinal = 2)
239
private String name;
240
241
@JSONField(format = "yyyy-MM-dd", ordinal = 3)
242
private Date birthDate;
243
244
@JSONField(serialize = false)
245
private String password;
246
247
@JSONField(alternateNames = {"email_address", "mail"})
248
private String email;
249
250
@JSONField(required = true)
251
private String username;
252
253
// getters and setters...
254
}
255
256
// Class-level configuration
257
@JSONType(
258
naming = PropertyNamingStrategy.SnakeCase,
259
orders = {"id", "name", "email"},
260
ignores = {"password", "internalField"}
261
)
262
public class Customer {
263
private Long id;
264
private String name;
265
private String email;
266
private String password;
267
private String internalField;
268
269
// getters and setters...
270
}
271
272
// Constructor support
273
public class Product {
274
private final String name;
275
private final double price;
276
277
@JSONCreator
278
public Product(@JSONField(name = "product_name") String name,
279
@JSONField(name = "product_price") double price) {
280
this.name = name;
281
this.price = price;
282
}
283
284
// getters...
285
}
286
287
// Builder pattern support
288
@JSONBuilder
289
public class Order {
290
private String id;
291
private List<Item> items;
292
private double total;
293
294
public static OrderBuilder builder() {
295
return new OrderBuilder();
296
}
297
298
public static class OrderBuilder {
299
private Order order = new Order();
300
301
public OrderBuilder id(String id) {
302
order.id = id;
303
return this;
304
}
305
306
public OrderBuilder items(List<Item> items) {
307
order.items = items;
308
return this;
309
}
310
311
public Order build() {
312
return order;
313
}
314
}
315
}
316
317
// Unwrapped fields
318
public class Profile {
319
private String name;
320
321
@JSONField(unwrapped = true)
322
private Address address; // Fields from Address will be flattened
323
}
324
325
public class Address {
326
private String street;
327
private String city;
328
private String country;
329
}
330
331
// Result JSON for Profile:
332
// {"name": "John", "street": "123 Main St", "city": "NYC", "country": "USA"}
333
334
// Custom serialization
335
public class CustomUser {
336
@JSONField(serializeUsing = CustomUserWriter.class)
337
private UserData userData;
338
}
339
340
// Performance optimization
341
@JSONCompiled
342
@JSONType(naming = PropertyNamingStrategy.SnakeCase)
343
public class HighVolumeData {
344
private String id;
345
private long timestamp;
346
private double value;
347
}
348
```
349
350
### Advanced Configuration Examples
351
352
```java
353
// Polymorphic type handling
354
@JSONType(seeAlso = {Circle.class, Rectangle.class})
355
public abstract class Shape {
356
protected String color;
357
}
358
359
public class Circle extends Shape {
360
private double radius;
361
}
362
363
public class Rectangle extends Shape {
364
private double width;
365
private double height;
366
}
367
368
// Multiple alternate names
369
public class FlexibleUser {
370
@JSONField(alternateNames = {"user_name", "username", "login", "user_id"})
371
private String name;
372
373
@JSONField(alternateNames = {"user_age", "age_years", "years_old"})
374
private int age;
375
}
376
377
// Complex date formatting
378
public class Event {
379
@JSONField(format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
380
private LocalDateTime startTime;
381
382
@JSONField(format = "yyyy-MM-dd")
383
private LocalDate eventDate;
384
385
@JSONField(format = "HH:mm")
386
private LocalTime duration;
387
}
388
389
// Conditional serialization
390
public class ConditionalData {
391
@JSONField(serialize = true, deserialize = false)
392
private String writeOnly;
393
394
@JSONField(serialize = false, deserialize = true)
395
private String readOnly;
396
397
@JSONField(serialize = true, deserialize = true)
398
private String readWrite;
399
}
400
```