Fastjson2 特性配置 Feature

在使用 Fastjson2 处理 JSON 数据时,我们经常需要对序列化反序列化的行为进行微调。Feature 就是用来实现这些控制的强大工具。本文将带你从零开始掌握 Fastjson2 的特性配置。

什么是 Feature?

Feature 是 Fastjson2 提供的一组配置选项,用于控制 JSON 处理的细节行为。通过 parseFeaturewriteFeature 预定义常量,我们可以轻松地启用或禁用特定的处理特性。

核心特性详解

1. 字段命名风格控制

FieldBased - 基于字段的序列化

 import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

public class FeatureDemo {
    public static void main(String[] args) {
        Product product = new Product();
        product.setPrice(100);
        product.setQuantity(3);
        // internalCode 作为内部状态,没有公开的 setter

        // 默认序列化(基于 Getter)
        String defaultJson = JSON.toJSONString(product);
        System.out.println("默认序列化: " + defaultJson);

        // FieldBased 序列化(基于字段)
        String fieldBasedJson = JSON.toJSONString(product, 
            JSONWriter.Feature.FieldBased);
        System.out.println("字段序列化: " + fieldBasedJson);
    }
}

class Product {
    private double price;
    private int quantity;
    private String internalCode = "SECRET001";  // 直接初始化,不需要 setter
    
    public double getPrice() { 
        return price; 
    }
    
    public void setPrice(double price) { 
        this.price = price; 
    }
    
    public int getQuantity() { 
        return quantity; 
    }
    
    public void setQuantity(int quantity) { 
        this.quantity = quantity; 
    }
    
    // 注意:internalCode 没有 getter
    
    public double getTotal() {
        return price * quantity;
    }
}

上面的输出内容为:

默认序列化: {"price":100.0,"quantity":3,"total":300.0}
字段序列化: {"internalCode":"SECRET001","price":100.0,"quantity":3}
默认:序列化 getter 方法(包括计算出来的 total)
FieldBased:序列化 字段本身(包括隐藏的 internalCode)
所以:
默认输出:price、quantity、total(计算值)
字段输出:price、quantity、internalCode(隐藏字段)

2. 日期格式化

WriteDateUseDateFormat - 日期格式化输出

import java.util.Date;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

public class DateFormatDemo {
    public static void main(String[] args) {
        Order order = new Order();
        order.setOrderId("ORD001");
        order.setCreateTime(new Date());

        // 默认:使用时间戳
        String defaultJson = JSON.toJSONString(order);
        System.out.println("默认: " + defaultJson);

        // 启用日期格式化
        String formattedJson = JSON.toJSONString(order, "yyyy-MM-dd HH:mm:ss");
        System.out.println("格式化: " + formattedJson);
    }
}

class Order {
    private String orderId;
    private Date createTime;
    // getters/setters 省略...
}

输出内容

默认: {"createTime":"2026-05-07 14:46:47.322","orderId":"ORD001"}
格式化: {"createTime":"2026-05-07 14:46:47","orderId":"ORD001"}

3. 空值处理

WriteNulls - 包含空值字段

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

public class NullValueDemo {
    public static void main(String[] args) {
        Product product = new Product();
        product.setId(1001);
        product.setName("笔记本电脑");
        // description 为 null

        // 默认:忽略 null 字段
        String defaultJson = JSON.toJSONString(product);
        System.out.println("忽略null: " + defaultJson);

        // 启用 WriteNulls:保留 null 字段
        String withNullsJson = JSON.toJSONString(product, 
            JSONWriter.Feature.WriteNulls);
        System.out.println("保留null: " + withNullsJson);
    }
}

class Product {
    private int id;
    private String name;
    private String description;
    // getters/setters 省略...
}

4. 反序列化特性配置

SupportClassForName - 启用安全模式

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;

public class ParseFeatureDemo {
    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"张三\",\"age\":30}";

        // 默认配置反序列化
        User user1 = JSON.parseObject(jsonStr, User.class);
        System.out.println(user1.getName());

        // 启用特定解析特性
        User user2 = JSON.parseObject(jsonStr, User.class,
            JSONReader.Feature.IgnoreSetNullValue);
        System.out.println("忽略setNull后: " + user2);
    }
}

组合使用多个 Feature

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

public class CombinedFeatureDemo {
    public static void main(String[] args) {
        User user = new User();
        user.setName("李四");
        user.setAge(28);
        user.setEmail(null);

        // 同时使用多个 Feature
        String json = JSON.toJSONString(user, 
            JSONWriter.Feature.FieldBased,
            JSONWriter.Feature.WriteNulls);

        System.out.println("组合配置: " + json);
    }
}

常见 Feature 速查表

特性名称说明适用场景
WriteNulls输出 null 值字段前端需要完整字段结构
FieldBased基于字段序列化处理私有字段
WriteDateUseDateFormat日期格式化为字符串可读性要求高
IgnoreErrorGetter忽略 getter 异常容错处理
SortField按字段名排序统一输出格式
PrettyFormat格式化输出调试和日志

最佳实践

  1. 按需配置:不要一次性启用所有 Feature,只添加真正需要的特性
  2. 统一配置:在项目入口或配置类中统一定义 Feature 组合
  3. 性能考虑:某些特性(如 PrettyFormat)会影响性能,生产环境谨慎使用
  4. 向后兼容:修改 Feature 配置前确认不影响现有系统

总结

Fastjson2 的 Feature 机制为我们提供了灵活的控制能力,通过合理配置可以轻松应对各种 JSON 处理需求。从最简单的空值控制到复杂的序列化行为定制,Feature 都能帮你优雅地实现。

建议在开发过程中多尝试不同的 Feature 组合,找到最适合你项目的配置方案。