序列化:Parcelable、Serializable

1、什么是序列化,实现序列化的目的是什么?

序列化就是为了 实现将对象状态转换为可保持或传输的格式的过程。

2、目的主要有以下三点:

1)永久性保存对象,保存对象的字节序列到本地文件中;

2)通过序列化对象在网络中传递对象;

3)通过序列化在进程间传递对象。

3、为什么说Parcelable 比Serializable更高效

Serializable is a standard Java interface. You simply mark a class Serializable by implenting the interface, and Java will automatically serialize it in certain situations.

Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.

从上可以看Serializable是java标准的,Parcelable是android提供的。

1)在使用内存的时候,Parcelable 类比Serializable性能高,所以推荐使用Parcelable类。
2).Serializable在序列化的时候采用了大量的反射,并且会产生大量的临时变量,从而产生过高的负载,而Parcelable没有这种情况。
3).但是,Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管Serializable效率低点, 也不提倡用,但在这种情况下,还是建议你用Serializable 。

4、实现
1 Serializable 的实现,只需要继承  implements Serializable 即可。这只是给对象打了一个标记,系统会自动将其序列化。
2 Parcelabel 的实现,需要在类中添加一个静态成员变量 CREATOR,这个变量需要继承 Parcelable.Creator 接口。

下面是Google给的例子:

public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };
     
     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }


5、实现例子

下面只给出关键部分代码,Person类跟Book类分别用了两种方式:

Person.java

package com.tutor.objecttran;
import java.io.Serializable;
public class Person implements Serializable {
	private static final long serialVersionUID = -7060210544600464481L; 
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

Book.java
package com.tutor.objecttran;
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable {
	private String bookName;
	private String author;
	private int publishTime;
	
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public int getPublishTime() {
		return publishTime;
	}
	public void setPublishTime(int publishTime) {
		this.publishTime = publishTime;
	}
	
	public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
		public Book createFromParcel(Parcel source) {
			Book mBook = new Book();
			mBook.bookName = source.readString();
			mBook.author = source.readString();
			mBook.publishTime = source.readInt();
			return mBook;
		}
		public Book[] newArray(int size) {
			return new Book[size];
		}
	};
	
	public int describeContents() {
		return 0;
	}
	public void writeToParcel(Parcel parcel, int flags) {
		parcel.writeString(bookName);
		parcel.writeString(author);
		parcel.writeInt(publishTime);
	}
}


则在发送的时候可以这样:

//Serializeable传递对象的方法  
    public void SerializeMethod(){  
        Person mPerson = new Person();  
        mPerson.setName("frankie");  
        mPerson.setAge(25);  
        Intent mIntent = new Intent(this,ObjectTranDemo1.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putSerializable(SER_KEY,mPerson);  
        mIntent.putExtras(mBundle);  
          
        startActivity(mIntent);  
    }  
    //Pacelable传递对象方法  
    public void PacelableMethod(){  
        Book mBook = new Book();  
        mBook.setBookName("Android Tutor");  
        mBook.setAuthor("Frankie");  
        mBook.setPublishTime(2010);  
        Intent mIntent = new Intent(this,ObjectTranDemo2.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mBook);  
        mIntent.putExtras(mBundle);  
          
        startActivity(mIntent);  
    }  


接收的时候则为:

Person mPerson = (Person)getIntent().getSerializableExtra(ObjectTranDemo.SER_KEY);  

Book mBook = (Book)getIntent().getParcelableExtra(ObjectTranDemo.PAR_KEY);  


5、Serializable存储本地实现例子

Person类实现了serializable

public class Person implements Serializable {
	private static final long serialVersionUID = 2352771880324639355L;

	public String name;
	public String address;
	public int age;

	public Person(String name, String addresss, int age) {
		this.name = name;
		this.address = addresss;
		this.age = age;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("name:" + name + ",");
		builder.append("address:" + address + ",");
		builder.append("age:" + age + "\n");
		return builder.toString();
	}
}

测试主程序:

public static void main(String[] args) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		Person person1 = new Person("张三", "广东深圳", 20);
		Person person2 = new Person("李三", "山东日照", 24);
		try {
			// 写
			File file = new File("E:/temp/1.txt");
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();

			ArrayList<Person> list = new ArrayList<Person>();
			list.add(person1);
			list.add(person2);

			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(list);

			// 读
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			ArrayList<Person> list2 = (ArrayList<Person>) ois.readObject();
			for (int i = 0; i < list2.size(); i++) {
				System.out.println("person:" + list2.get(i).toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (oos != null) {
					oos.close();
				}
				if (fis != null) {
					fis.close();
				}
				if (ois != null) {
					ois.close();
				}
			} catch (Exception e2) {
			}
		}

	}


相关引用:

http://blog.csdn.net/androidzhaoxiaogang/article/details/8172539

http://blog.csdn.net/android_tutor/article/details/5740845


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值