Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

2020/12/31 23:41 · java ·  · 0评论

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?

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}

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

Use serialize and deserialize methods in SerializationUtils from commons-lang.

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.

You can use ObjectMapper

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectClass object = objectMapper.readValue(data, ObjectClass.class);
本文地址:http://java.askforanswer.com/java-object-to-byte-and-byte-to-object-converter-for-tokyo-cabinet.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!