Android 序列化

2018-08-07  本文已影响0人  海是倒过来的天_67f2

序列化简单的说就是将运行时的对象状态转换成二进制,然后进行保存到流,内存或者通过网络传输给其他端。

在Android开发中我们常常在Intent中携带数据,其中有时需要传递Serializable或者Parcelable的数据,比如说Intent.putExtra方法。

public Intent putExtra(String name, Parcelable value){...}

public Intent putExtra(String name, Serializable value){...}

也可以使用Binder传递数据。

1.Serializable接口

Serializable是Java提供的序列化接口,它是一个空的接口

public interface Serializable {

}

Serializable用来标示当前类可以被ObjectOutputStream序列化,以及被ObjectInputStream反序列化。

Serializable具有以下特点:

可序列化类中,未实现Serializable的属性状态无法被序列化以及反序列化。

也就是说,反序列化一个类的过程中,它的非可序列化的属性将会调用无参构造函数从新创造。

因此这个属性的无参构造函数必须可以访问,否则运行时会报错。

一个实现序列化的类,它的子类也是可以序列化的。

举例:

import java.io.Serializable;

/**

* Created by jie on 18-7-24.

*/

public class User implements Serializable {

    private static final long serialVersionUID= 54564546843154L;

    public User(){

    }

    String name;

    int id;

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

}

需要注意的是在实现序列化时,需要手动实在一个serialVersion,在这个类序列化时,运行时会保存它的版本号,在反序列化时,检查要反序列化的对象版本号是否一致,不一致的话会报InvalidClassException异常。

序列化和反序列化Serializable

Serializable的序列化与反序列化分别通过ObjectOutputStream和ObjectInputStream进行,代码实例如下:

/**

* 序列化对象

*

* @param obj

* @param path

* @return */synchronized public static boolean saveObject(Object obj, String path) {

    if (obj == null) {

        return false;

    }

    ObjectOutputStream oos = null;

    try {

        oos = new ObjectOutputStream(new FileOutputStream(path));

        oos.writeObject(obj);

        oos.close();

        return true;

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        if (oos != null) {

            try {

                oos.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

    return false;

}/**

* 反序列化对象

*

* @param path

* @param

* @return */@SuppressWarnings("unchecked ")synchronized public static T readObject(String path) {

    ObjectInputStream ojs = null;

    try {

        ojs = new ObjectInputStream(new FileInputStream(path));

        return (T) ojs.readObject();

    } catch (IOException | ClassNotFoundException e) {

        e.printStackTrace();

    } finally {

        close(ojs);

    }

    return null;

}

2.Parcelable接口

Parcelable接口是Android特有的序列化接口

public interface Parcelable {

    //writeToParcel() 方法中的参数,用于标识当前对象作为返回值返回    //有些实现类可能会在这时释放其中的资源    public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;

    //writeToParcel() 方法中的第二个参数,它标识父对象会管理内部状态中重复的数据    public static final int PARCELABLE_ELIDE_DUPLICATES = 0x0002;

    //用于 describeContents() 方法的位掩码,每一位都代表着一种对象类型    public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;

    //描述当前 Parcelable 实例的对象类型    //比如说,如果对象中有文件描述符,这个方法就会返回上面的 CONTENTS_FILE_DESCRIPTOR    //其他情况会返回一个位掩码    public int describeContents();

    //将对象转换成一个 Parcel 对象    //参数中 dest 表示要写入的 Parcel 对象    //flags 表示这个对象将如何写入    public void writeToParcel(Parcel dest, int flags);

    //实现类必须有一个 Creator 属性,用于反序列化,将 Parcel 对象转换为 Parcelable    public interface Creator {

        public T createFromParcel(Parcel source);

        public T[] newArray(int size);

    }

    //对象创建时提供的一个创建器    public interface ClassLoaderCreator extends Creator {

        //使用类加载器和之前序列化成的 Parcel 对象反序列化一个对象        public T createFromParcel(Parcel source, ClassLoader loader);

    }

}

实现了Parcelable接口的类在序列化和反序列化是会被转换成Parcel

Parcel是一个载体,它可以包含数据或者对象引用,然后通过IBinder在进程间传递数据

import android.os.Parcel;

import android.os.Parcelable;

/**

* Created by jie on 18-7-24.

*/

public class Animal implements Parcelable {

    String name;

    int id;

    public Animal(String name, int id){

        this.name = name;

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    @Override

    public int describeContents() {

        //几乎都返回0,除非当前对象存在文件描述时为1

        return 0;

    }

    //序列化

    @Override

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(name);

        dest.writeInt(id);

    }

    //反序列化

    public static final Creator CREATOR = new Creator() {

        //反序列化创建对象

        @Override

        public Animal createFromParcel(Parcel source) {

            return null;

        }

        //反序列化创建数组

        @Override

        public Animal[] newArray(int size) {

            return new Animal[0];

        }

    };

    protected Animal(Parcel dest){

        name = dest.readString();

        id = dest.readInt();

    }

}

3结论

Serialiable的使用比较简单,创建一个版本号即可,而Parcelable则相对复制一些,

一般来说保存在SD卡或者网络传输时使用Serializable即可,虽然效率较差,但是比较方便。

而在运行时数据传递一般使用Parcelable,比如Intent,Bundle等,Android底层做了优化处理,效率较高。

上一篇 下一篇

猜你喜欢

热点阅读