1

Appended are my little utility functions for serialising objects. I just encountered following problem:

I renamed a package and suddenly I get a java.lang.ClassCastException when opening my app and trying to read serialised data...

Can I somehow solve that? I would like my serialisations to be working after a renaming, can I do something to implement this? Via some versioning for example?

Here are my two simple functions I use currently:

public static String serialize(Object object)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try
    {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
        oos.close();
    } catch (IOException e)
    {
        L.e(StringUtil.class, e);
    }
    return Base64.encodeToString(baos.toByteArray(), 0);
}

public static <T> T deserialize(String serializedObject, Class<T> clazz)
{
    if (serializedObject == null)
        return (T)null;

    byte [] data = Base64.decode(serializedObject, 0);
    Object o = null;
    try
    {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
        o = ois.readObject();
        ois.close();
    }
    catch (IOException e)
    {
        L.e(StringUtil.class, e);
    }
    catch (ClassNotFoundException e) {
        L.e(StringUtil.class, e);
    }

    return (T)o;
}
prom85
  • 16,896
  • 17
  • 122
  • 242
  • If you had java.util.Date and java.sql.Date would you not want them to serialize differently? – Scary Wombat Nov 29 '16 at 07:39
  • You're right, so I at least need to do some manual action after renaming classes that may have been serialised and saved somewhere. Changed my question a little bit... As I still want to be able to rename classes and packages and somehow be able to read old serialised data. Any ideas on that? – prom85 Nov 29 '16 at 07:47
  • Possible duplicate of [How can I deserialize the object, if it was moved to another package or renamed?](http://stackoverflow.com/questions/2358886/how-can-i-deserialize-the-object-if-it-was-moved-to-another-package-or-renamed) – MordechayS Nov 29 '16 at 08:10

1 Answers1

0

I can suggest next options:

  • add support to your deserialize method to deal with old package names
    • convert byte [] data to String
    • replace old package name with new in deserialized data (with regexp)
    • continue to deserialize with ObjectInputStream
qwazer
  • 7,174
  • 7
  • 44
  • 69