fastjson2 Documentation

repository·main·Indexed 26 days ago

https://github.com/alibaba/fastjson2

A high-performance, next-generation JSON library for Java optimized for JDK 8-21. It supports text-based JSON and binary JSONB formats, providing modules for Kotlin, Spring 5.x, and Spring 6.x, as well as a compatibility module for fastjson 1.2.x. Key features include JSONB serialization, customizable behavior via JSONWriter and JSONReader features, and field-level control using @JSONField and @JSONType annotations.

Tokens
97K
Snippets
135
Records
228
Agent score
83%

What's inside fastjson2

  1. Overview of Fastjson2 Project Structure

    main

    Fastjson2 is a high-performance JSON library for Java supporting both JSON and JSONB (binary JSON) formats. The project is organized into several modules:

    • core/: The main library (requires JDK 8+).
    • fastjson1-compatible/: Provides the Fastjson 1.x API compatibility layer.
    • kotlin/: Provides Kotlin extension functions and DSL.
    • extension-spring5/ & extension-spring6/: Integrations for Spring frameworks.
    • extension/: Base extensions for technologies like Arrow, ClickHouse, Geo, and Retrofit.
    • extension-jaxrs/: JAX-RS integration.
    • extension-solon/: Solon framework integration.
  2. Understand JSONWriter implementations in fastjson2

    main

    Fastjson2 uses different JSONWriter implementations depending on the serialization target and features requested:

    • JSONWriterUTF16: The default implementation used when calling JSON.toJSONString().
    • JSONWriterUTF8: The default implementation used when calling JSON.toJSONBytes(). It is also used when calling JSON.toJSONString() in combination with JSONWriter.Feature.OptimizedForAscii.
    • JSONWriterPretty: A wrapper implementation used when JSONWriter.Feature.PrettyFormat is enabled.
    • JSONWriterJSONB: Used when serializing to the JSONB format. It implements the same API to support both JSON and JSONB protocols.
  3. JSONB Binary Format Overview

    main

    JSONB is a high-performance binary representation of JSON. It is designed to be:

    • Compact: Small integers (-16 to 47) use only 1 byte.
    • Schema-less: Does not require a pre-defined schema.
    • Type-rich: Supports all standard JSON types plus binary data.
    • Symbol table enabled: Supports optional key compression for repeated field names.
    • Multi-encoding: Supports UTF-8, UTF-16, ASCII, or GB18030 for strings.
  4. Configure serialization and deserialization with Features

    main

    Fastjson 2.x uses two distinct feature sets to control behavior:

    • JSONWriter.Feature: Configures serialization (writing JSON).
    • JSONReader.Feature: Configures deserialization (reading JSON).

    You can apply these features globally during method calls or locally via annotations on specific fields or classes.

  5. Understand JSONReader implementations for different input types

    main

    The JSONReader class is the core implementation for reading JSON data in fastjson2. Depending on your input format, fastjson2 uses specific subclasses to optimize performance:

    • JSONReaderUTF16: Processes char[] input. In JDK 8, String inputs are converted to char[] and handled by this implementation. In JDK 9+, it is also used when coder=1.
    • JSONReaderUTF8: Processes UTF-8 encoded byte[] input.
    • JSONReaderASCII: A subclass of JSONReaderUTF8 used for coder=0 optimization in JDK 9 and later.
    • JSONReaderJSONB: Used when the input is in JSONB format, allowing the same API to handle both JSON and JSONB protocols.
  6. Understand JSONWriter implementations for serialization

    main

    Fastjson2 uses different JSONWriter implementations depending on the serialization method and desired output format. Understanding these helps in choosing the right API for performance optimization:

    • JSONWriterUTF16: The default implementation used when calling JSON.toJSONString.
    • JSONWriterUTF8: The default implementation used when calling JSON.toJSONBytes. It is also used when JSON.toJSONString is combined with the JSONWriter.Feature.OptimizedForAscii feature.
    • JSONWriterPretty: A wrapper implementation used when JSONWriter.Feature.PrettyFormat is enabled to provide formatted/indented output.
    • JSONWriterJSONB: The implementation used when serializing to the jsonb format, allowing the same API to handle different protocols.
  7. Upgrade to FASTJSON v2 using Compatibility Mode

    main

    You can upgrade to FASTJSON v2 without changing your existing code by using Compatibility Mode. This mode uses the original com.alibaba.fastjson package name. Note that for deep usage scenarios, full compatibility is not guaranteed, so thorough testing is required.

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>${fastjson2.version}</version>
    </dependency>
  8. Integrate Fastjson2 with Spring MVC 6.x and below

    main

    For Spring MVC 6.x and earlier, use the configureMessageConverters method to add FastJsonHttpMessageConverter to the list of converters. It is recommended to add it at index 0 to ensure it takes precedence.

    @Configuration
    public class FastJsonWebMvcConfiguration extends WebMvcConfigurationSupport {
    
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            FastJsonConfig config = new FastJsonConfig();
            config.setDateFormat("yyyy-MM-dd HH:mm:ss");
            config.setCharset(StandardCharsets.UTF_8);
    
            converter.setFastJsonConfig(config);
            converters.add(0, converter);
        }
    }
  9. Use FieldBased mode for maximum speed

    main

    Enabling FieldBased mode allows the library to access fields directly instead of through getter/setter methods. Note that this accesses private fields via reflection/ASM and may not work in all environments.

    Impact: Medium

    String json = JSON.toJSONString(user, JSONWriter.Feature.FieldBased);
    User user = JSON.parseObject(json, User.class, JSONReader.Feature.FieldBased);