This is an simple example with the LibGDX Vector3-class:
package de.vatterger.entitysystem.util.serializer;
import com.badlogic.gdx.math.Vector3;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
//This Serializer works with Vector3 only, you need to change all the types to your specific class
public class Vector3Serializer extends Serializer<Vector3>{
//This method constructs an object of the specified type from the data you put into the output in "write(...)"
@Override
public Vector3 read(Kryo kryo, Input in, Class<Vector3> vectorClass) {
//create new Object and read in the values in the same order you've written them
return new Vector3(in.readFloat(), in.readFloat(), in.readFloat());
}
//This method serializes an object by writing the relevant data to the output.
@Override
public void write(Kryo kryo, Output out, Vector3 vec) {
//write values into output
out.writeFloat(vec.x);
out.writeFloat(vec.y);
out.writeFloat(vec.z);
}
}
You can also write objects and many different primitive types, just have a look at the methods of Input/Output:
You can also use other serializers inside your serializer like this:
package de.vatterger.entitysystem.util.serializer;
import com.artemis.utils.Bag;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import static com.esotericsoftware.kryo.serializers.DefaultArraySerializers.*;
//This will serialize the artemis-odb Bag class, a ArrayList-like data structure
public class BagSerializer extends Serializer<Bag<?>>{
//other serializer
ObjectArraySerializer oas = new ObjectArraySerializer();
public BagSerializer() {
//set some options
//There can be different objects in this array!
oas.setElementsAreSameType(false);
//And they could be null!
oas.setElementsCanBeNull(true);
}
@Override
public Bag<?> read(Kryo kryo, Input in, Class<Bag<?>> bagClass) {
Object[] content = kryo.readObject(in, Object[].class, oas);
Bag<Object> bag = new Bag<Object>(content.length);
for (int i = 0; i < content.length; i++) {
bag.add(content[i]);
}
return bag;
}
@Override
public void write(Kryo kryo, Output out, Bag<?> bag) {
kryo.writeObject(out, bag.getData(), oas);
}
}
Then just register your object with an instance of your Serializer:
kryo.register(Vector3.class, new Vector3Serializer());