Unlock Fastjson: Inside Its High‑Performance Serialization Engine

This article dissects Alibaba's Fastjson library, explaining its architecture, core modules, project structure, serialization and deserialization processes, ASM‑based performance optimizations, AutoType security mechanisms, and streaming API, while providing code examples and practical insights for Java developers.

DeWu Technology
DeWu Technology
DeWu Technology
Unlock Fastjson: Inside Its High‑Performance Serialization Engine

Overview

Fastjson is Alibaba's open‑source high‑performance JSON serialization library, known for the fastest speed on small data. Version 1.x is deprecated and replaced by Fastjson 2.x, but 1.x remains widely used in China. Understanding its architecture helps engineers improve software design practice.

Core Module Architecture

The framework consists of five layers: User Interface, Configuration Management, Serialization Engine, Deserialization Engine, and Security Module. The User Interface provides facade classes to simplify usage. The Configuration layer allows runtime behavior tuning. The Serialization Engine implements the core serialization logic, while the Deserialization Engine handles parsing. The Security Module offers black‑/white‑list checks and other safety features.

Project Structure

Key packages and classes include:

com.alibaba.fastjson : core API and data structures (e.g., JSON.java as the main entry point).

com.alibaba.fastjson.serializer : serialization module (e.g., JSONSerializer.java, SerializeConfig.java, ObjectSerializer.java).

com.alibaba.fastjson.parser : deserialization module (e.g., DefaultJSONParser.java, JSONLexer.java, JavaBeanDeserializer.java).

com.alibaba.fastjson.annotation : annotation definitions such as @JSONField and @JSONType.

com.alibaba.fastjson/</code>
<code>├── JSON.java                # Core entry class</code>
<code>├── annotation/              # Annotation definitions</code>
<code>├── asm/                     # ASM bytecode optimization library</code>
<code>├── parser/                  # Parser module</code>
<code>│   ├── DefaultJSONParser.java  # Default JSON parser</code>
<code>│   ├── JSONLexer.java          # Lexical analyzer interface</code>
<code>│   └── deserializer/          # Deserializer implementations</code>
<code>├── serializer/               # Serializer module</code>
<code>│   ├── JSONSerializer.java     # JSON serializer</code>
<code>│   ├── SerializeConfig.java   # Serialization configuration</code>
<code>│   └── ObjectSerializer.java  # Object serializer interface</code>
<code>├── spi/                     # SPI extension mechanism</code>
<code>├── support/                 # Framework support</code>
<code>└── util/                    # Utility classes

Serialization Process

Serialization follows these steps:

Find the appropriate serializer.

Parse JavaBean fields.

Convert field values and build the JSON string.

The facade method JSON.toJSONString() creates a JSONSerializer which delegates to the selected ObjectSerializer. For JavaBeans, JavaBeanSerializer or an ASM‑generated serializer is used. The SerializeWriter buffers output using thread‑local char[] and byte[] arrays for high efficiency.

public static String toJSONString(Object object) {</code>
<code>    return toJSONString(object, SerializeConfig.globalInstance, null, null, DEFAULT_GENERATE_FEATURE);</code>
<code>}</code>
<code>public static String toJSONString(Object object, SerializeConfig config, SerializeFilter[] filters, String dateFormat, int defaultFeatures, SerializerFeature... features) {</code>
<code>    SerializeWriter out = new SerializeWriter(null, defaultFeatures, features);</code>
<code>    try {</code>
<code>        JSONSerializer serializer = new JSONSerializer(out);</code>
<code>        serializer.write(object); // core serialization call</code>
<code>        return out.toString();</code>
<code>    } finally {</code>
<code>        out.close();</code>
<code>    }</code>
<code>}

The JSONSerializer.write() method checks for null, looks up the ObjectSerializer via getObjectWriter(), and delegates the actual field writing. Different strategies are applied for primitive types, collections, enums, and JavaBeans. Circular reference detection uses an IdentityHashMap<Object, SerialContext> to store already‑serialized objects and writes a $ref placeholder when a cycle is detected.

public void write(Object object) {</code>
<code>    if (object == null) {</code>
<code>        out.writeNull();</code>
<code>        return;</code>
<code>    }</code>
<code>    Class<?> clazz = object.getClass();</code>
<code>    ObjectSerializer writer = getObjectWriter(clazz);</code>
<code>    try {</code>
<code>        writer.write(this, object, null, null, 0);</code>
<code>    } catch (IOException e) {</code>
<code>        throw new JSONException(e.getMessage(), e);</code>
<code>    }</code>
<code>}

Deserialization Process

Deserialization starts from JSON.parseObject(), which creates a DefaultJSONParser. The parser selects an appropriate ObjectDeserializer from ParserConfig, then processes the JSON token stream using JSONLexer. For JavaBeans, JavaBeanDeserializer handles field matching, type conversion, and object instantiation. AutoType support allows the @type field to specify the concrete class, but it introduces security risks.

public static <T> T parseObject(String text, Class<T> clazz, int features) {</code>
<code>    if (text == null) return null;</code>
<code>    DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance(), features);</code>
<code>    T value = (T) parser.parseObject(clazz);</code>
<code>    parser.handleResovleTask(value);</code>
<code>    parser.close();</code>
<code>    return value;</code>
<code>}

The ParserConfig.checkAutoType() method validates the class name against black‑/white‑list hash codes to prevent unsafe deserialization. If AutoType is disabled, polymorphic fields (e.g., an Animal interface) cannot be restored without explicit type information.

public Class<?> checkAutoType(String typeName, Class<?> expectClass, int features) {</code>
<code>    if (typeName == null) return null;</code>
<code>    // length and hash checks …</code>
<code>    if (autoTypeSupport || expectClass != null) {</code>
<code>        // verify against deny/accept hash tables</code>
<code>        // load class if allowed</code>
<code>    }</code>
<code>    return clazz;</code>
<code>}

Streaming API

Fastjson provides a streaming API via JSONReader and JSONWriter for processing massive JSON files. It uses an 8 KB sliding buffer and a pull‑parsing model, emitting Java objects one by one so that memory consumption stays low.

try (JSONReader reader = new JSONReader(new InputStreamReader(new FileInputStream("huge-array.json"), StandardCharsets.UTF_8))) {</code>
<code>    reader.startArray();</code>
<code>    while (reader.hasNext()) {</code>
<code>        Order order = reader.readObject(Order.class);</code>
<code>        processOrder(order);</code>
<code>        orderRepository.save(order); // object can be GC'd immediately</code>
<code>    }</code>
<code>    reader.endArray();</code>
<code>}

Feature Highlights

ASM Performance Optimization : Generates bytecode at runtime to replace reflection, improving serialization speed by ~20%.

AutoType Mechanism : Embeds concrete class names in @type for polymorphic deserialization, but can lead to RCE if not properly restricted.

Streaming Parsing : Enables low‑memory processing of large JSON payloads.

Summary

Fastjson excels at fast JSON serialization/deserialization by using a layered architecture, ASM‑generated serializers, and a flexible configuration system. However, its AutoType feature poses serious security concerns; it should be disabled or used with safeMode and strict white‑list policies. For most projects without extreme performance demands, Jackson or Fastjson 2 (which disables AutoType by default) are safer alternatives.

References

FastJson 反序列化漏洞原理分析 (https://www.cnblogs.com/Only-xiaoxiao/p/17213248.html)

序列化与反序列化——FastJSON、Jackson、Gson性能测试 (https://zhuanlan.zhihu.com/p/529342385)

FASTJSON 2 Autotype机制介绍 (https://alibaba.github.io/fastjson2/autotype_cn.html)

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaserializationFastJSONDeserialization
DeWu Technology
Written by

DeWu Technology

A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.