Search code examples
serializationkryo

Collection Serialization with Kryo


I'm trying to use kryo to serialize and deserialize a java collection.

The serializetion method looks like this:

public <T> byte[] serialize(List<T> objectsToSerialize) {
CollectionSerializer cs = new CollectionSerializer();
Output output = new Output();
cs.write(kryo, output, objectsToSerialize);
return output.toBytes();
}

Now I would like to write the deserialization method but having trouble doing so. Basically the CollectionSerializer has a read method, but I can't understand how to use it (and the documentation is pretty poor as far as I can tell).

Any ideas?


Solution

  • If you are looking to just serialize a Collection to a file then the standard Kryo commands (such as kryo.writeClassAndObject) can handle that very adequately. For example the following program passes a collection of strings to the file "testfile" and back again

    public class TestClass{
    
    
        public static void main(String[] args) throws FileNotFoundException{
            serialize();
            deSerialize();
        }
    
        public static void serialize() throws FileNotFoundException{
            Collection<String>collection=new ArrayList<>();
    
            collection.add("This is a serialized collection of strings");
    
            Kryo kryo = new Kryo();
            Output output = new Output(new FileOutputStream("testfile"));
            kryo.writeClassAndObject(output, collection);
            output.close();
        }
    
        public static void deSerialize() throws FileNotFoundException{
            Collection<String>collection;
    
            Kryo kryo = new Kryo();
            Input input = new Input(new FileInputStream("testfile"));
            collection=(Collection<String>)kryo.readClassAndObject(input);
            input.close();
    
            for(String string: collection){
                System.out.println(string);
            }
    
        }
    
    
    }