公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

枚举

package com.meeno.boot.oa.employee.enums;

import com.alibaba.fastjson.annotation.JSONType;
import com.meeno.boot.oa.common.BaseEnum;
import com.meeno.boot.oa.common.json.EnumSerializer;
import com.meeno.boot.oa.common.json.EnumDeserializer;

/**
 * @description: 员工状态枚举
 * @author: Wzq
 * @create: 2020-03-13 16:30
 */
@JSONType(serializer = EnumSerializer.class, deserializer = EnumDeserializer.class, serializeEnumAsJavaBean = true)
public enum EmployeeStatusEnum implements BaseEnum {
    ON_THE_JOB(1),//在职
    DIMISSION(2)//离职
    ;


    private Integer code;

    EmployeeStatusEnum(Integer code) {
        this.code = code;
    }

    @Override
    public Integer getCode() {
        return this.code;
    }
}

EnumDeserializer.java

package com.meeno.boot.oa.common.json;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.meeno.boot.oa.common.BaseEnum;

import java.lang.reflect.Type;

public class EnumDeserializer implements ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object o) {
        final JSONLexer lexer = parser.lexer;
        Class cls = (Class) type;
        Object[] enumConstants = cls.getEnumConstants();
        if (BaseEnum.class.isAssignableFrom(cls)) {
            for (Object enumConstant : enumConstants) {
                BaseEnum baseEnum = (BaseEnum) enumConstant;
                if (lexer.intValue() == baseEnum.getCode()) {
                    return (T) baseEnum;
                }
            }
        }
        return null;

    }

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

EnumSerializer.java

package com.meeno.boot.oa.common.json;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.meeno.boot.oa.common.BaseEnum;

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


public class EnumSerializer implements ObjectSerializer {

    @Override
    public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type, int i) throws IOException {
        if (o instanceof BaseEnum) {
            BaseEnum baseEnum = (BaseEnum) o;
            jsonSerializer.out.write(baseEnum.getCode().toString());
        } else {
            jsonSerializer.out.writeEnum((Enum<?>) o);
        }

    }
}

posted on 2020-09-22 12:25  公众号/架构师与哈苏  阅读(1813)  评论(0编辑  收藏  举报