user1302575
user1302575

Reputation:

Serialize any Object

I tried doing this:

ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj); 

Where obj is a simple class I made:

class Car {
  int id;
  String color;
  //... 
}

However I get java.io.NotSerializableException

Is it possible to serialize just about any kind of java.lang.Object into byte array? Is so, how?

Update:

The class that will be "serialized" does not implement a Serializable interface; the idea behind this thing I am trying to do is that I'm trying to have a Databse-backed java.util.Map where objects put in the map are stored directly in the database, thus any kind of Object

I have also seen some Serialization framework, where to get around this "limitation" in serializing arbitrary Object, there is a class registration like:

kryo.register(SomeClass.class, 0); 

Not sure about this.

But what I'm quite sure is that I need to do:

Upvotes: 3

Views: 4328

Answers (3)

dcernahoschi
dcernahoschi

Reputation: 15230

It's not possible to use a java.io.ObjectOutputStream to serialize every Object.

From the javadoc of ObjectOutputStream

Only objects that support the java.io.Serializable interface can be written to streams.

If you absolutely need java objects serialization kryo worths a try. By default you just need to do:

Kryo kryo = new Kryo();
// ...
Output output = new Output(new FileOutputStream("file.bin"));
SomeClass someObject = ...
kryo.writeObject(output, someObject);
output.close();

Kryo doesn't require your classes to implement Serializable and you can provide separate Serializer for your classes to control the serialization form. But is optional.

The code kryo.register(SomeClass.class, 0); is optional too, it optimize the serialization process.

Upvotes: 2

Yilmaz Guleryuz
Yilmaz Guleryuz

Reputation: 9735

here comes generic ObjectSerializer for serialize/deserialize (adapted from Apache libs):

public class ObjectSerializer {

    private static final String TAG = "ObjectSerializer";

    public static String serialize(Serializable obj) {// throws IOException {
        if (obj == null) return "";
        try {
            ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
            ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
            objStream.writeObject(obj);
            objStream.close();
            return encodeBytes(serialObj.toByteArray());
        } catch (Exception e) {
            //throw WrappedIOException.wrap("Serialization error: " + e.getMessage(), e);
            Log.e(TAG, "Serialization error: " + e.getMessage());
            return null;
        }
    }

    public static Object deserialize(String str) {// throws IOException {
        if (str == null || str.length() == 0) return null;
        try {
            ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
            ObjectInputStream objStream = new ObjectInputStream(serialObj);
            return objStream.readObject();
        } catch (Exception e) {
            //throw WrappedIOException.wrap("Deserialization error: " + e.getMessage(), e);
            Log.e(TAG, "Deserialization error: " + e.getMessage());
            return null;
        }
    }

    public static String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }

        return strBuf.toString();
    }

    public static byte[] decodeBytes(String str) {
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i+=2) {
            char c = str.charAt(i);
            bytes[i/2] = (byte) ((c - 'a') << 4);
            c = str.charAt(i+1);
            bytes[i/2] += (c - 'a');
        }
        return bytes;
    }

}

Upvotes: 0

Rahul
Rahul

Reputation: 45040

Your Car class needs to implement the Serializable interface for you to be able to Serialize your object.

class Car implements Serializable {

Upvotes: 3

Related Questions