幾種Android資料序列化方案

來源:互聯網
上載者:User

標籤:bind   exception   ==   des   外掛程式   create   部分   lag   描述   

一、引言

  資料的序列化在Android開發中佔據著重要的地位,無論是在處理序間通訊、本機資料儲存又或者是網路資料轉送都離不開序列化的支援。而針對不同情境選擇合適的序列化方案對於應用的效能有著極大的影響。

  從廣義上講,資料序列化就是將資料結構或者是對象轉換成我們可以儲存或者傳輸的資料格式的一個過程,在序列化的過程中,資料結構或者對象將其狀態資訊寫入到臨時或者持久性的儲存區中,而在對應的還原序列化過程中,則可以說是產生的資料被還原成資料結構或對象的過程。

  這樣來說,資料序列化相當於是將我們原先的對象序列化概念做出了擴充,在對象序列化和還原序列化中,我們熟知的有兩種方法,其一是Java語言中提供的Serializable介面,其二是Android提供的Parcelable介面。而在這裡,因為我們對這個概念做出了擴充,因此也需要考慮幾種專門針對資料結構進行序列化的方法,如現在那些個開放API一般返回的資料都是JSON格式的,又或者是我們Android原生的SQLite資料庫來實現資料的本機存放區,從廣義上來說,這些都可以算做是資料的序列化。

二、Serializable介面

正如前面提到的,Serializable介面是Java語言的特性,是最簡單也是使用最廣泛的序列化方案之一,這邊需要注意的一點是Serializable介面是一個標識介面,無需實現方法,Java便會對這個對象進行序列化操作。

在這裡實現了Serializable介面的對象才可以序列化,將Java對象轉換成位元組序列,而對應的還原序列化則是將位元組序列恢複成Java對象的過程。

在需要序列化的類中會用到serialVersionUID去標識這個序列化對象,即僅當序列化後的資料中的SerialVersionUID與當前類的serialVersionUID相同時才能被正常的還原序列化。

import java.io.*;public class User implements Serializable{    private static final long serialVersionUID= 123456;    public int userId;    public String userName;    public boolean isMale;    public User(int userId,String userName,boolean isMale){        this.userId=userId;        this.userName=userName;        this.isMale = isMale;    }    public boolean toSerial(User user) throws IOException{        ObjectOutputStream out=null;        boolean status=false;        try{            out = new ObjectOutputStream(new FileOutputStream("cache.txt"));            out.writeObject(user);            status=true;            }catch(FileNotFoundException e){                System.out.println("NO FILE");            }finally{                if(out!=null)                    out.close();            }        return status;    }    public User toObject(String filename) throws IOException{        ObjectInputStream in=null;        boolean status=false;        User user=null;        try{            in = new ObjectInputStream(new FileInputStream(filename));            user=(User) in.readObject();            }catch(ClassNotFoundException e){            System.out.println("No file");        }finally{            if(in!=null)                in.close();        }        return user;    }    public static void main(String[] args) throws IOException{        User user = new User(0,"jake",true);        System.out.println(user.toSerial(user));        System.out.println(user.toObject("cache.txt").getClass());    }}

此外,需要注意的:靜態成員變數是屬於類而不屬於對象的,所以顯然它不會參與到對象的序列化過程中。其次用transient關鍵字標記的成員變數不參與到序列化過程中。最後,這種序列化方式是基於磁碟或者網路的。

三、Parcelable介面

Parcelable介面是Android API提供的介面,從某種程度上來說,它更適用於Android平台上。不同於Serializable,它是基於記憶體的,由於記憶體中讀寫速度高於磁碟,所以Parcelable介面被廣泛用於跨進程對象的傳遞。

下面貼上一個簡單的Parcelable介面的序列化過程:

import android.os.Parcel;import android.os.Parcelable;public class User implements Parcelable {    public int userId;    public String userName;    public boolean isMale;    public User(int userId,String userName,boolean isMale) {        this.userId=userId;        this.userName=userName;        this.isMale=isMale;    }        public static final Creator<User> CREATOR = new Creator<User>() {        @Override        public User createFromParcel(Parcel in) {            return new User(in);        }        @Override        public User[] newArray(int size) {            return new User[size];        }    };    public User(Parcel in) {        userId=in.readInt();        userName = in.readString();        isMale=in.readInt()==1;    }        @Override    public int describeContents() {        return 0;    }    @Override    public void writeToParcel(Parcel out, int flags) {        out.writeInt(userId);        out.writeString(userName);        out.writeInt(isMale?1:0);    }}

從上面可以看出,實現一個Parcelable介面,需要實現以下幾個方法:

1.建構函式:從序列化後的對象中建立原始對象

2.describeContents :介面內容的描述,一般預設返回0即可

3.writeToParcel:序列化的方法,將類的資料寫到parcel容器中

4.靜態parcelable.Creator介面,這個介面包含兩個方法

1)createFormParcel:還原序列化的方法,將Parcel還原成Java對象

2)newArray:提供給外部類還原序列化這個數組使用。

四、兩種對象序列化方法的對比

Serializable是Java中的序列化介面,其使用起來簡單但開銷較大(因為Serializable在序列化過程中使用了反射機制,故而會產生大量的臨時變數,從而導致頻繁的GC),並且在讀寫資料過程中,它是通過IO流的形式將資料寫入到硬碟或者傳輸到網路上。

而Parcelable則是以IBinder作為資訊載體,在記憶體上開銷比較小,因此在記憶體之間進行資料傳遞時,推薦使用Parcelable,而Parcelable對資料進行持久化或者網路傳輸時操作複雜,一般這個時候推薦使用Serializable。

另外Serializable在使用時比較簡單,而Parcelable在使用時需要手動去實現介面中的方法,為了規避使用Parcelable介面時的麻煩,我們下面介紹一個外掛程式,從而自動產生對應的代碼。

五、Parcelable外掛程式

為了避免寫大量的模板代碼,這邊介紹一個在Android Strudio中的外掛程式,Android Parcelable code generator。在Pulgins中下載並按照該外掛程式,接下來當我們需要用到Parcelable介面時,該外掛程式就能自動幫我們將類對象轉換成實現Parcelable介面的形式。

具體樣本如下,

/** * Created by DB on 2017/6/24. */public class BookItem {    public String mName;    public long mLastTime;    public String mTitle;    public String mPath;}

然後類似與產生getter和setter代碼那樣,我們就可以直接自動產生Parcelable形式的代碼,結果如下所示:

import android.os.Parcel;import android.os.Parcelable;/** * Created by DB on 2017/6/24. */public class BookItem implements Parcelable {    public String mName;    public long mLastTime;    public String mTitle;    public String mPath;    @Override    public int describeContents() {        return 0;    }    @Override    public void writeToParcel(Parcel dest, int flags) {        dest.writeString(this.mName);        dest.writeLong(this.mLastTime);        dest.writeString(this.mTitle);        dest.writeString(this.mPath);    }    public BookItem() {    }    protected BookItem(Parcel in) {        this.mName = in.readString();        this.mLastTime = in.readLong();        this.mTitle = in.readString();        this.mPath = in.readString();    }    public static final Parcelable.Creator<BookItem> CREATOR = new Parcelable.Creator<BookItem>() {        @Override        public BookItem createFromParcel(Parcel source) {            return new BookItem(source);        }        @Override        public BookItem[] newArray(int size) {            return new BookItem[size];        }    };}

有了這個外掛程式,使用Parcelable介面顯然方便了許多(可以偷好多懶)

六、資料的序列化方案

下面講到的是廣義上的序列化方案,不同於前面兩種狹義或者說是對象序列化方案,接下來的幾種方案針對於資料的傳輸和預存程序中的序列化方案

1.SQLite 

SQLite主要用於儲存複雜的關係型資料,Android支援原生支援SQLite資料庫相關操作(SQLiteOpenHelper),不過由於原生API介面並不友好,所以產生了不少封裝了SQLite的ORM架構。

2.SharedPreferences

SharedPreferences是Android平台上提供的一個輕量級儲存API,一般用於儲存常用的配置資訊,其本質是一個索引值對儲存,支援常用的資料類型如boolean、float、int、long以及String的儲存和讀取。

使用SharedPreferences讀取和儲存操作如下:

讀取:

1) 擷取Sharedpreferences對象

SharedPreferences mPreferences = context.getCSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);

2.通過SharedPReferences對象讀取儲存在SharedPreferences中的資料

mPreferences.getBoolean(key,defValue);

儲存:

1)擷取SharedPreferences.Editor對象

SharedPreferences.Editor editor = mPreferences.edit();

2)通過SharedPreferences.Editor對象寫入資料到SharedPreferences中。

mEditor.putBoolean(key,b);

3)調用commit函數將寫入的資料提交,從而完成資料存放區操作。

mEditor.commit();

3.JSON

JSON是一種輕量級的資料互動格式,由於其相對於XML,體積更小,在網路上傳輸時更加介紹瀏覽,被廣泛用於移動端。大部分APP與服務端的通訊都是使用JSON格式進行互動。

幾種Android資料序列化方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.