Loading...

FastJSON 使用注意事项:JSON.toJSONString 与 Null 值处理

FastJSON 是由阿里巴巴开源的一套高性能 JSON 处理器。相较于其他 JSON 处理器(如 Gson、Jackson)以及 Java 原生的序列化/反序列化方式,FastJSON 在性能上通常具有显著优势。

使用 JSON.toJSONString 的注意事项

1. Null 值属性的默认行为(潜在的“坑”)

  • 现象: 当使用 JSON.toJSONString 将一个 Java 对象转换为 JSON 字符串时,如果该对象的某些属性值为 nullFastJSON 默认会将这些属性从生成的 JSON 字符串中完全过滤掉(即不包含对应的 key)
  • 示例: 假设一个对象有三个属性 a, b, c,其中 a=1, b="hello", c=null。默认情况下,转换后的 JSON 字符串会是 {"a":1,"b":"hello"},属性 c 及其 null 值会被省略。
  • 潜在问题: 这种默认行为在某些场景下可能不符合预期(例如,需要明确区分 null 和字段不存在,或者下游系统要求完整的字段结构)。

2. 生成 JSON 字符串的两种主要方式

FastJSON 提供了两种核心方法将对象转换为 JSON 字符串:

  1. JSON.toJSONString(Object object)
    • 这是最常用的静态方法。
    • 直接作用于目标对象。
  2. JSONObject.toJSONString(Object object)
    • 通过 JSONObject 的静态方法实现。
    • 功能上与 JSON.toJSONString 基本相同。通常更推荐直接使用 JSON.toJSONString

3. 控制 Null 值输出的序列化特性

FastJSON 提供了特定的 SerializerFeature 来控制 null 值的序列化行为,避免其被默认过滤:

  • SerializerFeature.WriteMapNullValue

    • 作用: 强制输出值为 null 的字段。
    • 效果: 值为 null 的属性会以 key: null 的形式出现在 JSON 字符串中。
    • 适用场景: 适用于所有类型的 null 值(对象、数组、字符串、数字等)。
    • 用法示例:
      Map<String, Object> map = new HashMap<>(); map.put("a", 1); map.put("b", "hello"); map.put("c", null); String jsonString = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue); // 结果: {"a":1,"b":"hello","c":null}
  • SerializerFeature.WriteNullStringAsEmpty

    • 作用: 将值为 null 的字符串 (String) 字段序列化为空字符串 ""
    • 效果: 值为 nullString 类型属性会输出为 key: ""
    • 适用场景: 仅针对 String 类型。其他类型的 null 值(如 Integer, List 等)不会被处理(默认仍可能被过滤,除非同时使用 WriteMapNullValue)。
    • 用法示例:
      public class Message { private Integer id; private String content; // String 类型 // getters & setters } Message msg = new Message(); msg.setId(1); msg.setContent(null); // content 是 String 且为 null String jsonString = JSON.toJSONString(msg, SerializerFeature.WriteNullStringAsEmpty); // 结果: {"id":1,"content":""} (注意 content 是空字符串)

关键区别与选择

  • WriteMapNullValue: 保留所有 null 字段,显式输出为 null。适用于需要明确表示字段存在但值为空的场景。
  • WriteNullStringAsEmpty: String 类型的 null 转换为空字符串 ""。适用于特定要求字符串字段不能为 null 而必须是空字符串的场景。它不影响非 String 类型的 null 值。

注意事项

  • 如果需要处理String 类型null 值(如 Integer, Boolean, 自定义对象等),必须使用 WriteMapNullValue
  • 可以同时传递多个 SerializerFeature
    JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, ...);
  • 如果同时使用 WriteMapNullValueWriteNullStringAsEmpty
    • 对于 String 类型的 null 值,会应用 WriteNullStringAsEmpty,输出为 ""
    • 对于其他类型的 null 值,会应用 WriteMapNullValue,输出为 null
  • 可以通过配置 JSON.DEFAULT_GENERATE_FEATURE 来修改全局默认的序列化特性(包含 WriteMapNullValue),但这会影响所有未显式指定特性的序列化操作,需谨慎使用。
最后修改:2025 年 06 月 05 日
如果觉得我的文章对你有用,请随意赞赏