Loading AI tools
来自维基百科,自由的百科全书
Gson(又称Google Gson)是Google公司发布的一个开放原始码的Java库,主要用途为序列化Java物件为JSON字符串,或反序列化JSON字符串成Java物件。
Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或用户应用。
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相同
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.