fastjson Map反序列化类型丢失

xxb16uws  于 2021-11-27  发布在  Java
关注(0)|答案(2)|浏览(366)

你好,我是redis-replicator作者,报如下issue

  1. fastjson版本: 1.2.44
  2. java版本: jdk 1.8.151
  3. 重现代码
public class FastJSONEventSerializer implements Serializer<Event> {

    private static SerializeConfig config = new SerializeConfig();
    private static SerializerFeature[] sfeatures = { WriteEnumUsingToString,
        DisableCircularReferenceDetect, WriteClassName };
    private static Feature[] features = { Feature.DisableCircularReferenceDetect };

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

    @Override
    public Event read(byte[] bytes) {
        return (Event) JSON.parse(bytes, features);
    }

    @Override
    public byte[] write(Event event) {
        return JSONObject.toJSONBytes(event, config, sfeatures);
    }

    public static void main(String[] args) {
        Serializer<Event> serializer = new FastJSONEventSerializer();
        Map<String, String> v1 = new LinkedHashMap<>();
        v1.put("a","b");
        v1.put("c","d");
        Map<byte[], byte[]> v2 = new ByteArrayMap<>();
        v2.put(new byte[]{-12,31,23,2}, new byte[]{-12,31,23,3});
        v2.put(new byte[]{-12,31,23,3}, new byte[]{-12,31,23,2});
        MSetCommand command = new MSetCommand(v1, v2);
        System.out.println(command.getKv().getClass());
        System.out.println(command.getRawKv().getClass());
        command = (MSetCommand)serializer.read(serializer.write(command));
        System.out.println(command.getKv().getClass());
        System.out.println(command.getRawKv().getClass());
    }
}

输出

class java.util.LinkedHashMap
class com.moilioncircle.redis.replicator.util.ByteArrayMap
class java.util.HashMap
class java.util.HashMap

发现之前的类型分别为LinkedHashMap和ByteArrayMap,之后全变为HashMap了
相关的类代码MSetCommandByteArrayMap

6bc51xsx

6bc51xsx2#

不能用typereference,因为不知道具体的type,我的理解是map序列化的时候已经开启了WriteClassName, 那么反序列化的时候就应该用@type的信息,为什么没有用这个信息而反序列化成hashmap了呢

相关问题