dkunzler / esperandro

Easy SharedPreference Engine foR ANDROid
Other
180 stars 14 forks source link

Default serialiser without dependencies #50

Closed MFlisar closed 6 years ago

MFlisar commented 6 years ago

could you add a default serialiser that does not depend on anything special? No jackson and no gson?

I usually use following in all my projects:

public class SerializationUtil {

    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(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(e);
        } catch (ClassNotFoundException e) {
            L.e(e);
        }

        return (T) o;
    }
}

This could be packed into a small extension...

dkunzler commented 6 years ago

I'm not a huge fan of ObjectStream serialisation. I am willing to add some serializer without dependencies if you have a good idea for an implementation, but as you have seen in your other issue this is not very robust. JSON for example would also survive changes in fields of classes without runtime error.

MFlisar commented 6 years ago

I don't have an idea for a more simply serialisation currently, but I understand your concerns and it make sense to me. It's just two functions though, I have them in my local core library I use in all my projects, so I'm fine with this. Was just a suggestion