KJW
KJW

Reputation: 15251

Java: how to serialize a 3rd party library produced Java Object?

So I am using a proprietary java library in a project which I don't have access to source code.

It throws a Message object, and obviously I can't implement Serializable. It's generated throughout runtime.

what are my options? Is there a way to serialize the Message object into a byte array and back into the object?

UPDATE: I was able to serialize the object to JSON (http://code.google.com/p/json-io/) but couldn't convert it back to an object as it returns null. So I am trying to convert it to byte array using the code below. Still not working.

public byte[] toByteArray (Object obj)
{
  byte[] bytes = null;
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    ObjectOutputStream oos = new ObjectOutputStream(bos); 
    oos.writeObject(obj);
    oos.flush(); 
    oos.close(); 
    bos.close();
    bytes = bos.toByteArray ();
  }
  catch (IOException ex) {
    //TODO: Handle the exception
  }
  return bytes;
}

public Object toObject (byte[] bytes)
{
  Object obj = null;
  try {
    ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
    ObjectInputStream ois = new ObjectInputStream (bis);
    obj = ois.readObject();
  }
  catch (IOException ex) {
    //TODO: Handle the exception
  }
  catch (ClassNotFoundException ex) {
    //TODO: Handle the exception
  }
  return obj;
}

Upvotes: 2

Views: 1960

Answers (4)

duffymo
duffymo

Reputation: 308938

Sure, you just can't use the java.lang.Serializable mechanism.

Choose any format: XML, JSON, protocol buffer, or something else that might work for you.

Now you're responsible for both ends of the conversation: serialization and deserialization.

Upvotes: 2

Ingo Kegel
Ingo Kegel

Reputation: 48070

If the object is a Java bean, you can use java.beans.XMLEncoder and java.beans.XMLDecoder for serialization.

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

XStream is one way to go.

Upvotes: 2

DerMike
DerMike

Reputation: 16190

You could write a wrapper that is serializable and stores everything you need to recreate the Message object.

Upvotes: 3

Related Questions