Android序列化
Android序列化对象主要有两种方法,实现Serializable接口、或者实现Parcelable接口。实现Serializable接口是Java SE本身就支持的,而Parcelable是Android特有的功能,效率比实现Serializable接口高,而且还可以用在进程间通信(IPC)中。实现Serializable接口非常简单,声明一下就可以了。而实现Parcelable接口稍微复杂一些,但效率更高,推荐用这种方法提高性能。 android 中自定义的对象序列化的问题有两个选择一个是Parcelable,另外一个是Serializable。
一 序列化原因: 1.永久性保存对象,保存对象的字节序列到本地文件中; 2.通过序列化对象在网络中传递对象; 3.通过序列化在进程间传递对象。
二 至于选取哪种可参考下面的原则: 1.在使用内存的时候,Parcelable 类比Serializable性能高,所以推荐使用Parcelable类。 2.Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC。 3.Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管Serializable效率低点, 也不提倡用,但在这种情况下,还是建议你用Serializable 。
注意事项 1、Serializable 可用于简单对象,list对象传递,但是不能用于嵌套List对象传递,传递后为null。 2、Parcelable 1)实用复杂对象,以及嵌套传递, 2)Caused by: java.lang.RuntimeException: Parcel android.os.Parcel@4051d600: Unmarshalling unknown type code 70 at offset 424
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(path);
dest.writeInt(file_type);
dest.writeString(content);
dest.writeTypedList(files);
}
public Company createFromParcel(Parcel in) {
return new Company(in);
}
private Company(Parcel in) {
this.path = in.readString();
this.file_type = in.readInt();
this.content = in.readString();
this.files = new ArrayList<Company>();
in.readTypedList(files,Company.CREATOR);
}
|
如果createFromParcel方法中少写了一个 this.title = in.readString()或者写入跟读取对象类型不匹配;则会报如上的异常,也就是说方法中写入到邮包中的和从邮包中读取的数据一定要一致 3)嵌套List对象传递 public class Company implements Parcelable{ private String title; private String path; private String content; private int file_type; private ArrayList files; public ArrayList getFiles() { return files; } public void setFiles(ArrayList files) { this.files = files; } public int getFile_type() { return file_type; } public void setFile_type(int file_type) { this.file_type = file_type; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(path); dest.writeInt(file_type); dest.writeString(content); dest.writeTypedList(files); } public Company() {
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
}
public static final Parcelable.Creator<Company> CREATOR = new Parcelable.Creator<Company>() {
public Company createFromParcel(Parcel in) {
return new Company(in);
}
public Company[] newArray(int size) {
return new Company[size];
}
};
private Company(Parcel in) {
this.title = in.readString();
this.path = in.readString();
this.file_type = in.readInt();
this.content = in.readString();
this.files = new ArrayList<Company>();
in.readTypedList(files,Company.CREATOR);
}
}
|