[ACCEPTED]-Serialization of an object with Kryo (Custom Serializer)-kryo
I can tell from your example that you are 22 using Kryo v1. I suggest using Kryo v2.
You 21 can set a serializer for Map, like you have, and 20 then serialize each key and value. To serialize 19 each object, either write the data using 18 the Output class and read using the Input 17 class, or call methods on the Kryo instance 16 to have it handle the objects.
It would be 15 easier to use the built in MapSerializer. You 14 only need to customize serialization of 13 your Tile objects. You can have them extend 12 KryoSerializable or you can register a Serializer. Here 11 is an example...
public class Tile implements KryoSerializable {
int x, y;
Object something;
public void write (Kryo kryo, Output output) {
output.writeInt(x);
output.writeInt(y);
kryo.writeClassAndObject(output, something);
}
public void read (Kryo kryo, Input input) {
x = input.readInt();
y = input.readInt();
something = kryo.readClassAndObject(input);
}
}
Here is another example, using 10 a Serializer instead of KryoSerializable:
public class Tile {
int x, y;
Object something;
}
kryo.register(Tile.class, new Serializer<Tile>() {
public void write (Kryo kryo, Output output, Tile object) {
output.writeInt(object.x);
output.writeInt(object.y);
kryo.writeClassAndObject(output, object.something);
}
public Tile read (Kryo kryo, Input input, Class<Tile> type) {
Tile tile = new Tile();
kryo.reference(tile); // Only necessary if Kryo#setReferences is true AND Tile#something could reference this tile.
tile.x = input.readInt();
tile.y = input.readInt();
tile.something = kryo.readClassAndObject(input);
return tile;
}
});
This 9 is slightly more complicated in the read 8 method because of the call to Kryo#reference 7 before you use the Kryo instance to deserialize 6 child objects. This can be omitted if not 5 using references at all, or if you know 4 that the "something" object cannot 3 possibly reference the tile we have just 2 created. If you were only using Input to 1 read data, you wouldn't need to call Kryo#reference.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.