fastjson 泛型类中的泛型为枚举类型时,反序列化时不能自动转为枚举

emeijp43  于 3个月前  发布在  其他
关注(0)|答案(1)|浏览(67)

如题,1.2.28的fastjson存在此问题(之前的版本应该也存在)。
复现case如下:

public class DefaultJsonSerializer {

    private static final Charset CHARSET = Charset.forName("UTF-8");

    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public static <T> void serialize(T obj, OutputStream out) {
        JSONWriter writer = null;
        try {
            writer = new JSONWriter(new OutputStreamWriter(out, CHARSET.newEncoder().onMalformedInput(CodingErrorAction.IGNORE)));
            writer.config(SerializerFeature.QuoteFieldNames, true);
            writer.config(SerializerFeature.SkipTransientField, true);
            writer.config(SerializerFeature.SortField, true);
            writer.config(SerializerFeature.WriteClassName, true);
            writer.config(SerializerFeature.DisableCircularReferenceDetect, true);
            writer.writeObject(obj);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public static <T> T deserialize(byte[] in) {
        return (T) JSON.parse(in, 0, in.length, CHARSET.newDecoder(), Feature.AllowArbitraryCommas,
                Feature.IgnoreNotMatch, Feature.SortFeidFastMatch, Feature.DisableCircularReferenceDetect,
                Feature.AutoCloseSource);
    }

}

//===============   enum define  ==================

public enum EnumType {

    ONE(1, "1"),

    TWO(2, "2")
    ;

    private int code;
    private String desc;

    EnumType(int code, String desc){
        this.code = code;
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "EnumType{" +
                "code=" + code +
                ", desc='" + desc + '\'' +
                '}';
    }
}

//================ main ===========
public class EnumJsonSerialTest {

    public static void main(String[] args) {
        Map<EnumType, EnumType> map = new HashMap<>();
        map.put(EnumType.ONE, EnumType.TWO);

        serialTest(map);
    }

    private static void serialTest(Object object){
        System.out.println("序列化前的参数为:" + object);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try{
            DefaultJsonSerializer.serialize(object, bos);

            Object desRes = DefaultJsonSerializer.deserialize(bos.toByteArray());
            System.out.println("反序列化后的结果为:" + desRes);
        }finally {
            try{
                bos.close();
            }catch (IOException e){
            }
        }
    }
}

//=============== 运行结果 ================
序列化前的参数为:{EnumType{code=1, desc='1'}=EnumType{code=2, desc='2'}}
反序列化后的结果为:{ONE=TWO}

pbgvytdp

pbgvytdp1#

这个确实是一直不支持的,要支持还比较麻烦

相关问题