HA

Java 将对象序列化为字符串 读取字符串反序列化为对象

Java 将对象序列化为字符串 读取字符串反序列化为对象

import java.io.Serializable;

class test {
    public static String object2String(Object obj) {
        String objBody = null;
        ByteArrayOutputStream baops = null;
        ObjectOutputStream oos = null;

        try {
            baops = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baops);
            oos.writeObject(obj);
            byte[] bytes = baops.toByteArray();
            objBody = Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch(IOException e) {
            Log.e(tag, e.getMessage());
        } finally {
            try {
                if(oos != null)
                    oos.close();
                if(baops != null)
                    baops.close();
            } catch(IOException e) {
                Log.e(tag, e.getMessage());
            }
        }
        return objBody;
    }

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T getObjectFromString
            (String objBody, Class<T> clazz) {
        byte[] bytes = Base64.decode(objBody, Base64.DEFAULT);
        ObjectInputStream ois = null;
        T obj = null;
        try {
            ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            obj = (T) ois.readObject();
        } catch(IOException e) {
            Log.e(tag, e.getMessage());
        } catch(ClassNotFoundException e) {
            Log.e(tag, e.getMessage());
        } finally {
            try {
                if(ois != null)
                    ois.close();
            } catch(IOException e) {
                Log.e(tag, e.getMessage());
            }
        }

        return obj;
    }
}

reference

  1. Java 序列化学习 —— Object序列化成字符串
  2. 解决序列化中的问题java.io.StreamCorruptedException: invalid stream header:EFBFBDEF
  3. code