跳到主要內容

GSON 進階教學

GSON進階教學

完成基礎教學後,本章節教你如何處理在非正常情況下,如何完成反序列與序列動作。

  • 泛型轉換
  • 序列化與反序列化時,客製化輸入出JOSN字串@SerializedName
  • 忽略物件屬性輸出@Expose

泛型轉換

泛型做Json序列/反序列時,比較麻煩地方是泛型在運行期間相關的參數就會被抹除所以無法知道原來的類別。我們建立一個播放器(Play)類別,它為泛型的類型,它可撥放MP3、CD等等,所以建立一個CD媒介(CD)類別。Play使用類型為泛型T,

物件 屬性
播放器 Play 類型 type
CD媒介 CD 歌 songs
/**'
 *  播放器
 * @param 
 */
public class Play {
    T type ;
    public Play(T t){
        this.type = t;
     }

    @Override
    public String toString() {
        return this.type.toString();
    }
}
/**
 * CD 音樂物件
 */
public class CD {
    private List songs ;

    public CD(String ...songs){
        this.songs = new ArrayList() ;
        for(String song : songs){
            this.songs.add(song) ;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder() ;
        sb.append("");
        for(String s:songs){
            sb.append(""+s+",\r\n");
        }
        sb.append("");
        return sb.toString();
    }
}

我們現在建立cd01歌曲資料,用toJson序列可以正常動作,但是要做反序列直接轉換無法正常動作,所以需要利用TypeToken來建立類型,在fromJson回傳正確類型,

public class PlayTest {

    public static void main(String[] ags){
        CD cd01 = new CD("lemon tree ","She","I want it that way");
        Play play = new Play

序列化與反序列化時,名稱不同

之前的範例都是JSON欄位名稱與物件名稱相同,如果輸入JSON欄位名稱不同時,可以利用@SerializedName去定義輸入欄位名稱,但是需要Gson 2.4 版之後開始支援的 alternate 屬性。

  1. 反序列與序列相同設定
    物件屬性可能跟JSON不一樣,如書(Book)屬性為bid,但是JSON字串欄位為bookID,這種狀況就可以使用@SerializedName(value=”bookID”)來定義接收/與輸入屬性為bookID,
public class BookTest {

    public  static void main(String[] args){
           //input json string
        String book_json = "{\"bookID\":\"9626344946\",\"title\":\"The Moonlit Road and Other Stories\",\"author\":\" Bierce, Ambrose/ Croker, B. M./ Crawford, F. Marion/ Le Fanu, Joseph Sheridan/ Keeble, Jonathan (NRT)\"}";
        Gson gson = new Gson();
        Type type = new TypeToken(){}.getType();
        Book book = gson.fromJson(book_json,type);
        // convert Book object 
        System.out.println(book.toString()) ;
        // output json string
        System.out.println(gson.toJson(book)) ;
    }

}

/**
 * name : 書明細
 */
public class Book {
    @Expose(serialize = false, deserialize = false)
    @SerializedName(value="bookID")
    private String bid;
    private String title;
    private String author;

    public Book(String bid, String title, String author)  {
        this.bid = bid ;
        this.title = title ;
        this.author = author ;
    }

    public String getBId() {
        return bid;
    }

    public void setBId(String id) {
        this.bid = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer() ;
        sb.append("") ;
        sb.append("bid:"+bid+"\n") ;
        sb.append("title:"+title+"\n") ;
        sb.append("author:"+author+"\n") ;
        sb.append("") ;
        return sb.toString() ;
    }

}

結果:
bid:9626344946
title:The Moonlit Road and Other Stories
author: Bierce, Ambrose/ Croker, B. M./ Crawford, F. Marion/ Le Fanu, Joseph Sheridan/ Keeble, Jonathan (NRT)

{“bookID”:”9626344946”,”title”:”The Moonlit Road and Other Stories”,”author”:” Bierce, Ambrose/ Croker, B. M./ Crawford, F. Marion/ Le Fanu, Joseph Sheridan/ Keeble, Jonathan (NRT)”}

2.如果JSON輸出與輸入名稱不相同時,就需要alternate 來定義反序列輸入欄位名稱,如 @SerializedName(value=”bookID”, alternate = “ISBN”),那輸入會以ISBN或是bookID為bid的欄位。

public class BookTest {

    public  static void main(String[] args){
        String book_json = "{\"ISBN\":\"9626344946\",\"title\":\"The Moonlit Road and Other Stories\",\"author\":\" Bierce, Ambrose/ Croker, B. M./ Crawford, F. Marion/ Le Fanu, Joseph Sheridan/ Keeble, Jonathan (NRT)\"}";
        Gson gson = new Gson();
        Type type = new TypeToken(){}.getType();
        Book book = gson.fromJson(book_json,type);
        System.out.println(book.toString()) ;

    }

}

/**
 * name : 書明細
 */
public class Book {
    @Expose
    @SerializedName(value="bid",alternate = "ISBN")
    private String bid;
    private String title;
    private String author;

    public Book(String bid, String title, String author)  {
        this.bid = bid ;
        this.title = title ;
        this.author = author ;
    }

    public String getBId() {
        return bid;
    }

    public void setBId(String id) {
        this.bid = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer() ;
        sb.append("") ;
        sb.append("bid:"+bid+"\n") ;
        sb.append("title:"+title+"\n") ;
        sb.append("author:"+author+"\n") ;
        sb.append("") ;
        return sb.toString() ;
    }
}

結果:
bid:9626344946
title:The Moonlit Road and Other Stories
author: Bierce, Ambrose/ Croker, B. M./ Crawford, F. Marion/ Le Fanu, Joseph Sheridan/ Keeble, Jonathan (NRT)

{“bookID”:”9626344946”,”title”:”The Moonlit Road and Other Stories”,”author”:” Bierce, Ambrose/ Croker, B. M./ Crawford, F. Marion/ Le Fanu, Joseph Sheridan/ Keeble, Jonathan (NRT)”}

忽略物件屬性輸出@Expose

介紹最後一種情況當JAVA物件有些敏感資料不想要輸出字串時,可以使用Gson的@Expose註解標示,提供兩種標示serialize和deserialize,預設為true,也就是當沒有定義@Expose表示都要輸出欄位。
@Expose: serialize/deserialize預設為true

屬性 serialize deserialize
Expose true true
Expose false false
Expose false true
Expose true false

####參考資料
1. https://bng86.gitbooks.io/android-third-party-/content/gson.html
2. http://j796160836.pixnet.net/blog/post/30530326-%E7%9E%AD%E8%A7%A3json%E6%A0%BC%E5%BC%8F
3. http://blog.csdn.net/zzp_403184692/article/details/8266575
4. https://jimwayne.blogspot.tw/2016/09/gson.html

留言

這個網誌中的熱門文章

GSON基礎教學

GSON 前言 JSON是很常見的資料交換格式,在JAVA領域常用處理JSON的函式庫:GSON、FastXML和JSON-B,本章節會以GSON為主,學習目標如下 JSON格式說明 GSON 套件函式 GSON: 物件轉換JSON字串 GSON: JSON字串轉換物件 JSON 格式說明 JSON全名為JavaScript Object Notation,它是一種輕量級的資料交換格式,會大為流行的理由,主要是他比傳統用xml更輕巧且容易處理, JSON表達方式物件會用大括弧{},陣列則是用中括號[]。 用JSON字串來表達Employee的物件內容,由JSON字串可以知道物件name、age、sex和salary屬性。 JSON表示員工資料方式: {“name”:”Jack Bryant”, “age”:18, “sex”:”M”,”salary”:3500.00} JSON陣列表示方式: 跟我們使用JAVA的陣列方式類似,內容值可以是數字’、文字、布林、陣列、物件、null等等。 範例: 字串: [“紅”、”橙”、”黃”、”綠”、”青”、”藍”、”紫”} 布林: [true, true, false, false, true, true] GSON 套件函式 Gson為google所發布的函式庫,主要將物件與json字串之間的轉換時方便使用。當我們將JAVA物件轉換成JSON字串稱為 序列化 ,JSON字串轉換至JAVA物件稱為 反序列化 。 GSON: 物件轉換JSON字串 有了JSON基本概念後,我們進入本章重點,首先我們需要建立員工類別(Employee),定義如下 物件 屬性 員工類別 Employee name 名字 age 年紀 sex 性別 salary 薪水 /** * name:員工類別 */ public class Employee implements Serializable { //constructor public Employee(String name, double salary){ this.name = name; this.sala...

PHP與Python搭配

今天介紹如何利用php網頁呼叫目錄下的python程式工作或是資料交換,本人整理的方法有兩種 使用system()、exec()、shell_exec()呼叫程式 (1) string system ( string return_var ] ) 參考網址 官網解釋system()用來執行外部命令,返回為印出的結果,passthru()跟system()類似但是它不會返回結果。 範例1. 利用system執行ls指定並顯示在網頁上,無法使用變數保留ls的結果 檔案名稱: psystem.php $jsondata= system("ls -al", $result); 結果: (2) exec() : string exec ( string output [, int &$return_var ]] ) 參考網址 範例2. 利用exec執行python程式並可以回傳json格式給前端網頁做處理並顯示。我們ptopy.php就是可以看到callpy()為執行py的函式,它執行完pyEx01.py會將結果給$jsondata變數,做後面json解析。 檔案名稱: ptopy.php function callpy() { $jsondata= exec("/usr/bin/python pyEx01.py"); return $jsondata ; } $jsondata= callpy(); echo $jsondata ; echo " " ; $obj = json_decode($jsondata) ; echo "name:".$obj-> { 'name'} .',' ; echo "id:".$obj-> { 'id'} ; 檔案名稱: pyEx01.py import sys ...

JavaBean 和POJO

前言 今天介紹JavaBean和POJO的不同,這兩個名詞在JAVA文章常常被拿來使用以及討論。在JDK1.1時候釋出才有的一個標準架構,很多時候常常被搞混,所以我們特別開闢一章來加以討論。POJO規範在企業級應用已經廣大的被使用的規範。 解釋 POJO : 全名為Plain-old-Java-object,只需要繼承Object就可以,沒有特定規定,只要建立的類別有setter/getter方法都可以稱為POJO JavaBean: JavaBean通常用來封裝多個物件成為單獨物件使用,規範比較嚴格,規則如下 規則 說明 1 需要實作序列(Serializable/Externalizable) 2 不能有參數的建構子( no-arg constructor) 3 需要有公用setter/getter 4 屬性必須要私人(private) 5 屬於特定POJO規則 比較 所有的JavaBean都為POJO,但是所有的POJO不一定為JavaBean 都可以當作重複元件 都必須序列化 特性都為可用性、易用性和持久化使用 - 應用 由圖我們可以知道POJO在應用程式中,主要用來存取資料庫資料達到持久化的目的,並提供給商業邏輯流程處理使用。這種POJO的架構提供程式人員開發時的可以很有規則將資料封裝並加以使用。 範例1. JavaBean(以員工為實例) JavaBean建立員工物件,可以發現Employee物件建構子沒有任何參數,屬性為私有化並setter/getter的命名方式。 //實作序列化 public class Employee implements java.io.Serializable{ private int id; private String name; //無參數建構子 public Employee(){} //以下實作setter/getter public void setId(int id){this.id=id;} public int getId(){return id;} public void setName(String ...