alibaba.fastjson自定义枚举Enum序列化

一、过程

  1. 创建枚举型接口
import com.alibaba.fastjson.annotation.JSONType;

/**
 * 自定义JSON序列化枚举的接口
 */
@JSONType(serializer = EnumBaseSerializer.class)
public interface EnumBase{
    Integer getId();
    String getName();
}

2. 自定义枚举序列化类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义枚举JSON序列化类
 */
public class EnumBaseSerializer implements ObjectSerializer {
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object instanceof EnumBase) {
            Map map = new HashMap<Integer,String>();
            EnumBase enuma = (EnumBase) object;
            map.put("id",enuma.getId());
            map.put("name",enuma.getName());
            out.writeString(JSON.toJSONString(map));
        } else {
            out.writeEnum((Enum<?>) object);
        }
    }
}

3. 建立测试枚举

import com.alibaba.fastjson.annotation.JSONType;

// 自定义序列化类
@JSONType(serializeEnumAsJavaBean = true,serializer = EnumBaseSerializer.class)
public enum Gender implements EnumBase{

    MALE(1,"男"),
    FEMALE(2,"女");

    private Integer id;
    private String name;
    Gender(Integer id,String name){
        this.id = id;
        this.name = name;
    }
    public Integer getId(){
        return this.id;
    }
    public String getName(){
        return this.name;
    }

    /**
     * 根据ID,返回Name
     * @param id
     * @return
     * @throws Exception
     */
    public static String getNameById(Integer id)throws Exception{
        return Gender.getById(id).getName();
    }
    /**
     * 根据ID,返回实例
     * @param id
     * @return
     * @throws Exception
     */
    public static Gender getById(Integer id)throws Exception{
        //return Gender.values();
        for(Gender singleEnum:Gender.values()){
            if(singleEnum.getId()==id){
                return singleEnum;
            }
        }
        throw new Exception(Gender.class.getName()+" 未知枚举项: " + id);
    }
}

4.自定义测试类2

import lombok.Data;

@Data
public class TestToJson {
    private String name = "测试";
    private Gender gender = Gender.FEMALE;
    private Gender[] genders = Gender.values();
}

5.Main测试类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;

import java.util.ArrayList;
import java.util.List;

public class App {
    public static void main(String args[]){
        try{
            System.out.println("Hello World!");
            System.out.println("id 1= " + Gender.getNameById(1));
            System.out.println("id 2= " + Gender.getNameById(2));

            Gender g = Gender.MALE;

            System.out.println("JSON ENUM: " + JSON.toJSONString(Gender.values()));
            System.out.println("JSON CLASS: " + JSON.toJSONString(new TestToJson()));
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }

    }
}

测试可以通过。

分享到:更多 ()