1

希望大家都没问题。将不可序列化的对象转换为字节数组

我只是想知道,如何将non-serializable对象转换为没有serialization的字节数组?

经过一段时间的搜索后,我知道它可以在C#中使用自定义库(如BinaryFormatter)等等。有什么图书馆可以完成Android的工作吗?

在此先感谢

NB:实现Serializable对象是不是一种选择,已经尝试过用它进行试验了很多。

回答

-1
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; 
} 
+0

对于不可序列化的对象,这是不可能的@Mobility – Odin

+0

没有序列化这种方法是没有用的..它会抛出'SerializationException' – Rohit

相关问题