Question

Hope everyone's okay.

I was just wondering, how can I convert a non-serializable object to a byte array without serialization?

After searching for a while I know it is possible in C# with the use of custom libraries (like BinaryFormatter) and so. Are there any libraries that will do the job in Android?

Thanks in advance

NB: Implementing Serializable to the object isn't a choice, already tried experimenting with it a lot.

No correct solution

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top