FASTJSON 2 is a high-performance and easy-to-use Java JSON processing library with extreme performance that far exceeds other popular JSON libraries.
—
High-performance features including JSONB binary format, JSONPath queries, schema validation, and custom filters. These capabilities extend beyond basic JSON processing to provide enterprise-grade functionality.
High-performance binary JSON format optimized for speed and size, ideal for data transmission and storage.
/**
* JSONB binary format operations
*/
public class JSONB {
/**
* Convert object to JSONB binary format
* @param object Object to serialize
* @return JSONB bytes
*/
public static byte[] toBytes(Object object);
/**
* Convert object to JSONB with symbol table
* @param object Object to serialize
* @param symbolTable Symbol table for optimization
* @return JSONB bytes
*/
public static byte[] toBytes(Object object, SymbolTable symbolTable);
/**
* Parse JSONB bytes to object
* @param bytes JSONB binary data
* @return Parsed object
*/
public static Object parseObject(byte[] bytes);
/**
* Parse JSONB bytes with offset and length
* @param bytes JSONB binary data
* @param offset Starting offset
* @param length Data length
* @return Parsed object
*/
public static Object parseObject(byte[] bytes, int offset, int length);
/**
* Parse JSONB bytes to specific class
* @param bytes JSONB binary data
* @param clazz Target class type
* @return Instance of specified class
*/
public static <T> T parseObject(byte[] bytes, Class<T> clazz);
/**
* Parse JSONB bytes to specific class with offset
* @param bytes JSONB binary data
* @param offset Starting offset
* @param length Data length
* @param clazz Target class type
* @return Instance of specified class
*/
public static <T> T parseObject(byte[] bytes, int offset, int length, Class<T> clazz);
/**
* Parse JSONB bytes with Type reference
* @param bytes JSONB binary data
* @param type Target type
* @return Instance of specified type
*/
public static <T> T parseObject(byte[] bytes, Type type);
/**
* Parse JSONB to JSONArray
* @param bytes JSONB binary data
* @return JSONArray instance
*/
public static JSONArray parseArray(byte[] bytes);
/**
* Parse JSONB to typed List
* @param bytes JSONB binary data
* @param clazz Element class type
* @return List of specified element type
*/
public static <T> List<T> parseArray(byte[] bytes, Class<T> clazz);
/**
* Debug JSONB binary format
* @param bytes JSONB binary data
* @return Human-readable format description
*/
public static String dump(byte[] bytes);
/**
* Extract type information from JSONB
* @param bytes JSONB binary data
* @return Type name string
*/
public static String typeName(byte[] bytes);
/**
* Check if bytes contain valid JSONB data
* @param bytes Binary data to check
* @return true if valid JSONB format
*/
public static boolean isValid(byte[] bytes);
/**
* Create symbol table from objects for optimization
* @param objects Objects to analyze for symbols
* @return SymbolTable for reuse
*/
public static SymbolTable symbolTable(Object... objects);
}Advanced path-based JSON data extraction and manipulation using JSONPath expressions.
/**
* JSONPath query operations
*/
public class JSONPath {
/**
* Extract values from JSON string using path expression
* @param json JSON string
* @param path JSONPath expression
* @return Extracted value(s)
*/
public static Object extract(String json, String path);
/**
* Evaluate path expression against object
* @param rootObject Root object to query
* @param path JSONPath expression
* @return Query result
*/
public static Object eval(Object rootObject, String path);
/**
* Set value at specified path in JSON string
* @param json JSON string
* @param path JSONPath expression
* @param value Value to set
* @return Modified JSON string
*/
public static String set(String json, String path, Object value);
/**
* Create compiled JSONPath instance for reuse
* @param path JSONPath expression
* @return Compiled JSONPath instance
*/
public static JSONPath of(String path);
/**
* Extract values using compiled path
* @param rootObject Root object to query
* @return Query result
*/
public Object extract(Object rootObject);
/**
* Set value using compiled path
* @param rootObject Root object to modify
* @param value Value to set
*/
public void set(Object rootObject, Object value);
/**
* Check if path exists in object
* @param rootObject Root object to check
* @return true if path exists
*/
public boolean contains(Object rootObject);
/**
* Remove value at path from object
* @param rootObject Root object to modify
* @return Removed value
*/
public Object remove(Object rootObject);
/**
* Get all matching paths in object
* @param rootObject Root object to analyze
* @return Set of matching paths
*/
public Set<String> paths(Object rootObject);
/**
* Set callback for path evaluation
* @param callback Callback to invoke during evaluation
*/
public void setCallback(PathCallback callback);
}
/**
* JSONPath configuration features
*/
public enum JSONPath.Feature {
/** Always return results as a list */
AlwaysReturnList,
/** Suppress exceptions during path evaluation */
SuppressExceptions,
/** Use native object types instead of JSON types */
UseNativeObject
}JSON Schema validation capabilities for ensuring data integrity and structure compliance.
/**
* Base JSON Schema validation
*/
public abstract class JSONSchema {
/**
* Validate object against schema
* @param object Object to validate
* @return Validation result
*/
public ValidateResult validate(Object object);
/**
* Check if object is valid against schema
* @param object Object to validate
* @return true if valid
*/
public boolean isValid(Object object);
/**
* Parse schema from JSON string
* @param schema Schema definition
* @return JSONSchema instance
*/
public static JSONSchema parse(String schema);
}
/**
* Object schema validation
*/
public class ObjectSchema extends JSONSchema {
/**
* Set required properties
* @param properties Array of required property names
* @return This schema for chaining
*/
public ObjectSchema required(String... properties);
/**
* Set property schemas
* @param name Property name
* @param schema Property schema
* @return This schema for chaining
*/
public ObjectSchema property(String name, JSONSchema schema);
}
/**
* String schema with pattern validation
*/
public class StringSchema extends JSONSchema {
/**
* Set minimum length constraint
* @param minLength Minimum string length
* @return This schema for chaining
*/
public StringSchema minLength(int minLength);
/**
* Set maximum length constraint
* @param maxLength Maximum string length
* @return This schema for chaining
*/
public StringSchema maxLength(int maxLength);
/**
* Set pattern constraint
* @param pattern Regular expression pattern
* @return This schema for chaining
*/
public StringSchema pattern(String pattern);
}
/**
* Validation result container
*/
public class ValidateResult {
/**
* Check if validation passed
* @return true if valid
*/
public boolean isSuccess();
/**
* Get validation error message
* @return Error message or null if valid
*/
public String getMessage();
}Extensible filter system for transforming data during serialization and deserialization.
/**
* Base filter interface
*/
public interface Filter {
}
/**
* Transform property names during serialization
*/
public interface NameFilter extends Filter {
/**
* Transform property name
* @param object Source object
* @param name Original property name
* @param value Property value
* @return Transformed property name
*/
String process(Object object, String name, Object value);
}
/**
* Transform property values during serialization
*/
public interface ValueFilter extends Filter {
/**
* Transform property value
* @param object Source object
* @param name Property name
* @param value Original property value
* @return Transformed property value
*/
Object process(Object object, String name, Object value);
}
/**
* Control property inclusion during serialization
*/
public interface PropertyFilter extends Filter {
/**
* Determine if property should be included
* @param object Source object
* @param name Property name
* @param value Property value
* @return true to include property
*/
boolean apply(Object object, String name, Object value);
}
/**
* Pre-processing filter executed before serialization
*/
public interface BeforeFilter extends Filter {
/**
* Process object before serialization
* @param object Source object
*/
void writeBefore(Object object);
}
/**
* Post-processing filter executed after serialization
*/
public interface AfterFilter extends Filter {
/**
* Process object after serialization
* @param object Source object
*/
void writeAfter(Object object);
}Usage Examples:
import com.alibaba.fastjson2.*;
import com.alibaba.fastjson2.schema.*;
import com.alibaba.fastjson2.filter.*;
// JSONB Binary Format
User user = new User("John", 30);
// Convert to binary
byte[] jsonbBytes = JSONB.toBytes(user);
System.out.println("JSONB size: " + jsonbBytes.length); // Much smaller than JSON
// Parse from binary
User parsedUser = JSONB.parseObject(jsonbBytes, User.class);
// Debug binary format
String dump = JSONB.dump(jsonbBytes);
System.out.println("JSONB structure: " + dump);
// JSONPath Queries
String json = """
{
"users": [
{"name": "John", "age": 30, "city": "NYC"},
{"name": "Jane", "age": 25, "city": "SF"},
{"name": "Bob", "age": 35, "city": "LA"}
]
}
""";
// Basic path extraction
Object allUsers = JSONPath.extract(json, "$.users");
Object firstUser = JSONPath.extract(json, "$.users[0]");
Object allNames = JSONPath.extract(json, "$.users[*].name");
// Filtered queries
Object adults = JSONPath.extract(json, "$.users[?(@.age >= 30)]");
Object nycUsers = JSONPath.extract(json, "$.users[?(@.city == 'NYC')]");
// Compiled paths for reuse
JSONPath namePath = JSONPath.of("$.users[*].name");
List<String> names = (List<String>) namePath.extract(JSON.parseObject(json));
// Path modification
String modified = JSONPath.set(json, "$.users[0].age", 31);
// Schema Validation
String schemaJson = """
{
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {"type": "string", "minLength": 2},
"email": {"type": "string", "pattern": "^[^@]+@[^@]+\\.[^@]+$"},
"age": {"type": "integer", "minimum": 0}
}
}
""";
JSONSchema schema = JSONSchema.parse(schemaJson);
// Validate objects
User validUser = new User("John", "john@example.com", 30);
User invalidUser = new User("", "invalid-email", -5);
ValidateResult validResult = schema.validate(validUser);
ValidateResult invalidResult = schema.validate(invalidUser);
System.out.println("Valid user: " + validResult.isSuccess()); // true
System.out.println("Invalid user: " + invalidResult.isSuccess()); // false
System.out.println("Error: " + invalidResult.getMessage());
// Custom Filters
// Name filter to transform property names
NameFilter snakeCaseFilter = (object, name, value) -> {
return name.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
};
// Value filter to mask sensitive data
ValueFilter passwordFilter = (object, name, value) -> {
if ("password".equals(name)) {
return "***masked***";
}
return value;
};
// Property filter to exclude null values
PropertyFilter nullFilter = (object, name, value) -> value != null;
// Apply filters during serialization
JSON.config(snakeCaseFilter, passwordFilter, nullFilter);
User userWithPassword = new User("John", "secret123");
userWithPassword.setEmail(null);
String filteredJson = JSON.toJSONString(userWithPassword);
// Result: {"user_name":"John","password":"***masked***"}
// Note: email field excluded because it's null
// Stream processing for large datasets
try (InputStream inputStream = new FileInputStream("large-data.json")) {
StreamReader reader = new StreamReader(inputStream);
reader.readObject((path, value) -> {
if (path.endsWith(".user.name")) {
System.out.println("Found user: " + value);
}
});
}// Complex path expressions
String complexJson = """
{
"store": {
"book": [
{"category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95},
{"category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99},
{"category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "price": 8.99}
],
"bicycle": {"color": "red", "price": 19.95}
}
}
""";
// Get all book prices
Object bookPrices = JSONPath.extract(complexJson, "$.store.book[*].price");
// Get books cheaper than $10
Object cheapBooks = JSONPath.extract(complexJson, "$.store.book[?(@.price < 10)]");
// Get fiction books
Object fictionBooks = JSONPath.extract(complexJson, "$.store.book[?(@.category == 'fiction')]");
// Get all prices (books and bicycle)
Object allPrices = JSONPath.extract(complexJson, "$..price");
// Get last book
Object lastBook = JSONPath.extract(complexJson, "$.store.book[-1]");
// Complex filtering with multiple conditions
Object expensiveFiction = JSONPath.extract(complexJson,
"$.store.book[?(@.category == 'fiction' && @.price > 10)]");// Programmatic schema creation
ObjectSchema userSchema = new ObjectSchema()
.required("name", "email")
.property("name", new StringSchema().minLength(2).maxLength(50))
.property("email", new StringSchema().pattern("^[^@]+@[^@]+\\.[^@]+$"))
.property("age", new IntegerSchema().minimum(0).maximum(150));
// Array schema
ArraySchema usersSchema = new ArraySchema()
.items(userSchema)
.minItems(1)
.maxItems(100);
// Nested object validation
ObjectSchema addressSchema = new ObjectSchema()
.required("street", "city")
.property("street", new StringSchema().minLength(1))
.property("city", new StringSchema().minLength(1))
.property("zipCode", new StringSchema().pattern("\\d{5}(-\\d{4})?"));
ObjectSchema userWithAddressSchema = new ObjectSchema()
.required("name", "address")
.property("name", new StringSchema())
.property("address", addressSchema);Install with Tessl CLI
npx tessl i tessl/maven-com-alibaba-fastjson2--fastjson2