Gson

本页使用了标题或全文手工转换
维基百科,自由的百科全书
Google Gson
開發者Google
首次发布2008年5月22日 (2008-05-22)
当前版本
  • 2.10.1 (2023年1月6日)[1]
編輯維基數據鏈接
源代码库 編輯維基數據鏈接
编程语言Java
操作系统跨平台
许可协议Apache License 2.0
网站github.com/google/gson

Gson(又称Google Gson)是Google公司發布的一个開放原始碼的Java库,主要用途為序列化Java物件為JSON字串,或反序列化JSON字串成Java物件。

歷史

Gson當初是為因應Google公司內部需求而由Google自行研發而來,但自從在2008年五月公開發布第一版後已被許多公司或使用者應用。

各版本發布時間

  • 2008年
    • 05月22日 版本 1.0
    • 06月18日 版本 1.0.1
    • 07月1日 版本 1.1
    • 07月18日 版本 1.1.1
    • 08月29日 版本 1.2
  • 2009年
    • 01月12日 版本 1.3 Beta
    • 04月1日 版本 1.3
    • 10月9日 版本 1.4
  • 2010年
    • 08月19日 版本 1.5
    • 11月24日 版本 1.6
  • 2011年
    • 04月12日 版本 1.7
    • 04月13日 版本 1.7.1
    • 11月13日 版本 2.0
    • 12月31日 版本 2.1
  • 2012年
    • 05月5日 版本 2.2
    • 05月5日 版本 2.2.1
    • 07月2日 版本 2.2.2
  • 2013年
    • 04月12日 版本 2.2.3
    • 05月13日 版本 2.2.4
  • 2014年
    • 08月11日 版本 2.3
    • 11月20日 版本 2.3.1
  • 2015年
    • 10月4日 版本 2.4
    • 11月24日 版本 2.5
  • 2016年
    • 02月11日 版本 2.6
    • 02月11日 版本 2.6.1
    • 02月26日 版本 2.6.2
    • 06月14日 版本 2.7
    • 10月27日 版本 2.8.0
  • 2017年
    • 05月30日 版本 2.8.1

使用方法

Gson的應用主要為toJson與fromJson兩個轉換函式,而在使用這種物件轉換之前需先建立好物件的類別以及其成員才能成功的將JSON字串成功轉換成相對應的物件。

  class Examples {
    private int answer1 = 100;
    private String answer2 = "Hello world!";
    Examples(){
    }     // default constructor
  }

序列化JAVA物件成JSON字串

   Examples example1 = new Examples();
   Gson gson = new Gson();
   String json = gson.toJson(example1);

==> json is {"answer1":100,"answer2":"Hello world!"}

反序列化JSON字串成對應的JAVA物件

Examples example2= gson.fromJson(json,Examples.class);

==> example2即與example1相同

物件example1透過toJson序列化JSON字串傳遞,再宣告一個物件example2為接收了JSON後透過fromJson反序列化成example2,故example1與example2相同

參考文獻

外部連結

  1. ^ Release 2.10.1. 2023年1月6日 [2023年1月12日].