FASTJSON 2 is a high-performance and easy-to-use Java JSON processing library with extreme performance that far exceeds other popular JSON libraries.
—
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.
Control individual field serialization and deserialization behavior with @JSONField annotation.
/**
* Field-level customization annotation
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONField {
/**
* Custom field name in JSON
* @return Custom name or empty for default
*/
String name() default "";
/**
* Field ordering for serialization
* @return Order value (lower values first)
*/
int ordinal() default 0;
/**
* Date format pattern for Date/LocalDateTime fields
* @return Format pattern (e.g., "yyyy-MM-dd HH:mm:ss")
*/
String format() default "";
/**
* Whether to include field in serialization
* @return true to serialize, false to skip
*/
boolean serialize() default true;
/**
* Whether to include field in deserialization
* @return true to deserialize, false to skip
*/
boolean deserialize() default true;
/**
* Alternative names for deserialization
* @return Array of alternative field names
*/
String[] alternateNames() default {};
/**
* Custom serializer class
* @return ObjectWriter class for custom serialization
*/
Class<? extends ObjectWriter<?>> serializeUsing() default Void.class;
/**
* Custom deserializer class
* @return ObjectReader class for custom deserialization
*/
Class<? extends ObjectReader<?>> deserializeUsing() default Void.class;
/**
* Mark field as required during deserialization
* @return true if field must be present
*/
boolean required() default false;
/**
* Unwrap nested object fields to parent level
* @return true to flatten nested object
*/
boolean unwrapped() default false;
}Configure entire classes with @JSONType annotation for global serialization behavior.
/**
* Class-level configuration annotation
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONType {
/**
* Property naming strategy
* @return Naming strategy enum
*/
PropertyNamingStrategy naming() default PropertyNamingStrategy.CamelCase;
/**
* Field ordering for serialization
* @return Array of field names in desired order
*/
String[] orders() default {};
/**
* Fields to include in serialization
* @return Array of field names to include
*/
String[] includes() default {};
/**
* Fields to ignore in serialization
* @return Array of field names to ignore
*/
String[] ignores() default {};
/**
* Polymorphic type handling
* @return Array of subclasses for type resolution
*/
Class<?>[] seeAlso() default {};
/**
* Custom serializer for this class
* @return ObjectWriter class for custom serialization
*/
Class<? extends ObjectWriter<?>> serializer() default Void.class;
/**
* Custom deserializer for this class
* @return ObjectReader class for custom deserialization
*/
Class<? extends ObjectReader<?>> deserializer() default Void.class;
/**
* Serialization filters to apply
* @return Array of filter classes
*/
Class<? extends Filter>[] serializeFilters() default {};
}Mark constructors and builder methods for object creation during deserialization.
/**
* Mark constructor or static method for deserialization
*/
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONCreator {
}
/**
* Enable builder pattern support
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONBuilder {
/**
* Builder class to use
* @return Builder class
*/
Class<?> builderClass() default Void.class;
/**
* Method name to create builder instance
* @return Static method name (default: "builder")
*/
String builderMethodName() default "builder";
/**
* Method name to build final object
* @return Instance method name (default: "build")
*/
String buildMethodName() default "build";
}Enable compilation optimizations for frequently used classes.
/**
* Enable compilation optimizations
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONCompiled {
}Enumeration of available naming strategies for automatic property name transformation.
/**
* Property naming strategies
*/
public enum PropertyNamingStrategy {
/** Keep original Java naming (default) */
CamelCase,
/** Capitalize first letter */
PascalCase,
/** Use underscores between words */
SnakeCase,
/** Convert to uppercase */
UpperCase,
/** Pascal case with spaces */
UpperCamelCaseWithSpaces,
/** Pascal case with underscores */
UpperCamelCaseWithUnderScores,
/** Pascal case with dashes */
UpperCamelCaseWithDashes
}Usage Examples:
import com.alibaba.fastjson2.annotation.*;
// Field-level customization
public class User {
@JSONField(name = "user_id", ordinal = 1)
private Long id;
@JSONField(ordinal = 2)
private String name;
@JSONField(format = "yyyy-MM-dd", ordinal = 3)
private Date birthDate;
@JSONField(serialize = false)
private String password;
@JSONField(alternateNames = {"email_address", "mail"})
private String email;
@JSONField(required = true)
private String username;
// getters and setters...
}
// Class-level configuration
@JSONType(
naming = PropertyNamingStrategy.SnakeCase,
orders = {"id", "name", "email"},
ignores = {"password", "internalField"}
)
public class Customer {
private Long id;
private String name;
private String email;
private String password;
private String internalField;
// getters and setters...
}
// Constructor support
public class Product {
private final String name;
private final double price;
@JSONCreator
public Product(@JSONField(name = "product_name") String name,
@JSONField(name = "product_price") double price) {
this.name = name;
this.price = price;
}
// getters...
}
// Builder pattern support
@JSONBuilder
public class Order {
private String id;
private List<Item> items;
private double total;
public static OrderBuilder builder() {
return new OrderBuilder();
}
public static class OrderBuilder {
private Order order = new Order();
public OrderBuilder id(String id) {
order.id = id;
return this;
}
public OrderBuilder items(List<Item> items) {
order.items = items;
return this;
}
public Order build() {
return order;
}
}
}
// Unwrapped fields
public class Profile {
private String name;
@JSONField(unwrapped = true)
private Address address; // Fields from Address will be flattened
}
public class Address {
private String street;
private String city;
private String country;
}
// Result JSON for Profile:
// {"name": "John", "street": "123 Main St", "city": "NYC", "country": "USA"}
// Custom serialization
public class CustomUser {
@JSONField(serializeUsing = CustomUserWriter.class)
private UserData userData;
}
// Performance optimization
@JSONCompiled
@JSONType(naming = PropertyNamingStrategy.SnakeCase)
public class HighVolumeData {
private String id;
private long timestamp;
private double value;
}// Polymorphic type handling
@JSONType(seeAlso = {Circle.class, Rectangle.class})
public abstract class Shape {
protected String color;
}
public class Circle extends Shape {
private double radius;
}
public class Rectangle extends Shape {
private double width;
private double height;
}
// Multiple alternate names
public class FlexibleUser {
@JSONField(alternateNames = {"user_name", "username", "login", "user_id"})
private String name;
@JSONField(alternateNames = {"user_age", "age_years", "years_old"})
private int age;
}
// Complex date formatting
public class Event {
@JSONField(format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private LocalDateTime startTime;
@JSONField(format = "yyyy-MM-dd")
private LocalDate eventDate;
@JSONField(format = "HH:mm")
private LocalTime duration;
}
// Conditional serialization
public class ConditionalData {
@JSONField(serialize = true, deserialize = false)
private String writeOnly;
@JSONField(serialize = false, deserialize = true)
private String readOnly;
@JSONField(serialize = true, deserialize = true)
private String readWrite;
}Install with Tessl CLI
npx tessl i tessl/maven-com-alibaba-fastjson2--fastjson2