views:

88

answers:

3

I need to convert objects to a byte[] to be stored in the Tokyo Cabinet key-value store. I also need to unbyte the byte[] to an Object when reading from the key-value store.

Are there any packages out there that will help me with this task? Or would the best solution to implement it myself?

+3  A: 

If your class extends Serializable, you can write and read objects through a ByteArrayOutputStream, that's what I usually do.

G B
All types included as variables in your class (and all types in those types, and so on) also need to be Serializable.
Dean J
Actually he'll need an ObjectOutputStream to wrap the BAOS too... But yeah, that's the easiest way to go.
Aviad Ben Dov
I'd consider using something other than Java's built-in serialization, too - JBoss serialization, JSerial, Avro, etc, or an XML format like XStream or Javolution marshalling plus gzip. Standard serialization is not particularly fast, and although its marginal space efficiency is good, there's quite a bit of per-stream overhead.
Tom Anderson
+2  A: 

You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[] in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer (expecting Serializable, and using ObjectOutputStream). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.

I guess you can copy the entire package and make use of it.

Bozho
+3  A: 
public static byte[] serialize(Object obj) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}
Thomas Mueller