【发布时间】:2016-05-20 18:27:13
【问题描述】:
我正在使用消息 api 在智能手机和智能手表之间发送消息。由于它只能发送字节数组作为数据,我想在发送时将对象转换为字节数组,并在接收时反转转换。
我使用了以下从互联网上获得的代码。但我得到了 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呢? -
非常感谢您的链接。使用 ApacheUtils 对我有用: 序列化:字节 [] 数据 = SerializationUtils.serialize(yourObject);反序列化:YourObject yourObject = (YourObject) SerializationUtils.deserialize(byte[] data)
标签: android serialization wear-os android-bundle