Kryo Serialization with nested HashMap with custom class

自古美人都是妖i 提交于 2019-12-11 11:53:50

问题


I am trying to user kryo to serialze a custom class which itself contains some custom objects, more specifically a HashMap of custom objects. I was wondering the proper way to handle something like this. Below is the class I am trying to serialize (Data), the classes which are nested, and my current kryo implementation. This is the right approach?

public class Data {
    int id,
    int name,
    ItemList items;
}

public Class ItemList {

    HashMap<String, Item> items;
}

public Class Item {

    String itemId;
    String itemName;
    String itemDesc;
}

kryo.register(Data.class, new Serializer<Data>() {
    public void write (Kryo kryo, Output output, Data object) {
        output.writeInt(object.id);
        output.writeInt(object.name);
        kryo.writeClassAndObject(output, items);
    }

    public Tile read (Kryo kryo, Input input, Class<Data> type) {
        Data data = new Data();
        kryo.reference(data);
        data.id = input.readInt();
        data.name = input.readString();
        data.items = kryo.readClassAndObject(input);
        return data;
    }
});

回答1:


You can use MapSerializer class. Like:

MapSerializer serializer = new MapSerializer();
kryo.register(HashMap.class, serializer);
kryo.register(LinkedHashMap.class, serializer);
serializer.setKeyClass(String.class, kryo.getSerializer(String.class));
serializer.setKeysCanBeNull(false);
serializer.setKeyClass(String.class, kryo.getSerializer(String.class));

More, you can get here http://kryo.googlecode.com/svn-history/r416/trunk/test/com/esotericsoftware/kryo/MapSerializerTest.java



来源:https://stackoverflow.com/questions/28157236/kryo-serialization-with-nested-hashmap-with-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!