0
我正在使用消息api在智能手机和智能手表之间发送消息。由于它只能将字节数组作为数据发送,因此我希望将对象转换为字节数组,同时在接收时发送和反转转换。如何将Android对象转换为字节数组并返回?
我已经使用了我从互联网上获得的下面的代码。但我得到java.io.NotSerializableException。有没有更好的方法来做到这一点?
我的对象将有一个字符串值和一个android包。两者都需要从一个设备发送并在另一端接收。
public static byte[] toByteArray(Object obj) throws IOException {
byte[] bytes = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
} finally {
if (oos != null) {
oos.close();
}
if (bos != null) {
bos.close();
}
}
return bytes;
}
public static Event toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Event obj = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bis);
obj = (Event) ois.readObject();
} finally {
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
}
return obj;
}
对象是可串行化的吗?说,为什么不让你的方法接收'Serializable obj'呢? – Budius
看看这里:http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array – Konstantin
非常感谢链接。使用ApacheUtils为我工作: 序列化: byte [] data = SerializationUtils.serialize(yourObject); 反串行化: YourObject yourObject =(YourObject)SerializationUtils.deserialize(byte [] data) – NewOne