Fastjson custom serialization


Fastjson Custom Serialization

1. Introduction

Fastjson supports multiple ways to customize serialization.

  • Customized serialization through @JSONField
  • Customized serialization through @JSONType
  • Customized serialization through SerializeFilter
  • Customized deserialization through ParseProcess

2. Use @JSONField configuration

You can configure @JSONField on fields or getter/setter methods. For example:

 public class VO {
      @JSONField(name="ID")
      private int id;
 }

or

 public class VO {
      private int id;

      @JSONField(name="ID")
      public int getId() { return id;}

      @JSONField(name="ID")
      public void setId(int value) {this.id = id;}
 }

See here for more: JSONField

3. Use @JSONType to configure

similar to JSONField , but JSONType is configured on the class, not on the field or getter/setter method.

4. Customized serialization through SerializeFilter

Customized serialization can be implemented using extended programming through SerializeFilter. fastjson provides a variety of SerializeFilter:

  • PropertyPreFilter determines whether to serialize based on PropertyName
  • PropertyFilter determines whether to serialize based on PropertyName and PropertyValue
  • NameFilter Modifies Key, if If you need to modify the Key and process return value, you can
  • ValueFilter Modify Value
  • BeforeFilter Add content at the front during serialization
  • AfterFilter Add content at the end during serialization
SerializeFilter filter = ...; // 可以是上面5个SerializeFilter的任意一种。
  JSON.toJSONString(obj, filter);

See more here: SerializeFilter

5. Customized deserialization through ParseProcess

Customized deserialization API ParseProcess