问题
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