1、什么叫序列化和反序列化
- 将对象和字节序列相互转换的过程
2、用处
- 将对象保存在本地
- 在网络上传输
- Intent和AIDL等中,传输数据类型有限,当要传输对象时,需要把对象序列化
3、android中两种方式实现序列化和反序列化
- Serializable接口
- Parcelable接口
4、实现方式,都要实现接口
- Serializable方式
新建一个类Products实现此接口
public class Products implements Serializable {
private String name;
private float price;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPrice(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
}
序列化,以Intent为例
Products products=new Products();
products.setName("apple");
products.setPrice(10);
Intent intent=new Intent(this,MainActivity.class);
intent.putExtra("o",products);
startActivity(intent);
反序列化,首先要获取传递的对象
Products products=(Products)getIntent().getSerializableExtra("o");
String name=products.getName();
float price=products.getPrice();
- Parcelable方式
新建一个类实现该接口,其中必须重写describeContents()和writeToParcel()方法和CREATOR
public class Product implements Parcelable {
private String name;
private float price;
public static final Parcelable.Creator<Product> CREATOR=new Parcelable.Creator<Product>()
{
@Override
public Product createFromParcel(Parcel parcel) {
Product product=new Product();
product.name=parcel.readString();
product.price=parcel.readFloat();
return product;
}
@Override
public Product[] newArray(int i) {
return new Product[i];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeFloat(price);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPrice(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
}
序列化
Product product=new Product();
product.setName("apple");
product.setPrice(10);
Intent intent=new Intent(this,MainActivity.class);
intent.putExtra("o",product);
startActivity(intent);
反序列化
Product product=(Product)getIntent().getParcelableExtra("o");
String name=product.getName();
float price=product.getPrice();
总结
Serializable比Parcelable实现简单,但是效率比不上后者。