FastJson自定义序列化器

[toc]

  1. 新建Class 实现 ObjectSerializer
/**
 * 自定义json序列化器
 * @author lizhichao
 * @description
 * @date 2019/10/21 17:45
 */
public class StringToJsonObjSerializer implements ObjectSerializer {

   /**
     * 
     * @param jsonSerializer 序列化器
     * @param o 字段值
     * @param o1 字段名
     * @param type 字段类型
     * @param i  特征
     * @throws IOException
     */

    @Override
    public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type, int i) throws IOException {
        SerializeWriter out = jsonSerializer.out;

        if (o == null) {
            out.writeNull();
            jsonSerializer.writeNull();
            return;
        }

        String s = o.toString();

        jsonSerializer.write(JSON.parse(s));
    }
}

  1. 实现 write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType,int features )
package com.alibaba.fastjson.serializer;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Interface representing a custom serializer for fastjson. You should write a custom serializer, if
 * you are not happy with the default serialization done by fastjson. You will also need to register
 * this serializer through {@link com.alibaba.fastjson.serializer.SerializeConfig#put(Type, ObjectSerializer)}.
 *
 * <pre>
 * public static class Result {
 *     public ResultCode code;
 * }
 * 
 * public static enum ResultCode {
 *     LOGIN_FAILURE(8), INVALID_ARGUMENT(0), SIGN_ERROR(17);
 *     public final int value;
 *     ResultCode(int value){
 *         this.value = value;
 *     }
 * }
 * 
 * public static class ResultCodeSerilaizer implements ObjectSerializer {
 *     public void write(JSONSerializer serializer, 
 *                       Object object, 
 *                       Object fieldName, 
 *                       Type fieldType,
 *                       int features) throws IOException {
 *         serializer.write(((ResultCode) object).value);
 *     }
 * }
 * 
 * SerializeConfig.getGlobalInstance().put(ResultCode.class, new ResultCodeSerilaizer());
 * 
 * Result result = new Result();
 * result.code = ResultCode.SIGN_ERROR;
 * String json = JSON.toJSONString(result, config); // {"code":17}
 * Assert.assertEquals("{\"code\":17}", json);
 * </pre>
 * @author wenshao[szujobs@hotmail.com]
 */
public interface ObjectSerializer {
    
    /**
     * fastjson invokes this call-back method during serialization when it encounters a field of the
     * specified type.
     * @param serializer 
     * @param object src the object that needs to be converted to Json.
     * @param fieldName parent object field name
     * @param fieldType parent object field type
     * @param features parent object field serializer features
     * @throws IOException
     */
    void write(JSONSerializer serializer, //
               Object object, //
               Object fieldName, //
               Type fieldType, //
               int features) throws IOException;
}

  1. 如何使用
    在字段上打上注解 @JSONField 并指定属性 serializeUsing 为自定义序列化器
public class User {
    @JSONField(serializeUsing = AgeVauleSerializer.class)
    private String info;
}

反序列化器

  1. 新建Class 实现 ObjectDeserializer
public class TimestampValueDeserializer implements ObjectDeserializer {

    @Override
    public Date deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        long timestamp = parser.getLexer().longValue();
        return new Date(timestamp);

    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

}
  1. 如何使用
    在字段上打上注解 @JSONField 并指定属性 deserializeUsing 为自定义序列化器
public class User {
    @JSONField(deserializeUsing = TimestampValueDeserializer.class)
    private Date data;
}

Q.E.D.