gson是google的產物,用于解決json數據解析比較繁瑣的問題。以前解析json需要層層解析,gson出現后解析往往只需幾行代碼。下面從簡單到復雜說說我對gson用法的理解。
### 一,簡單的json的解析
在使用之前當然要導入Gson的jar包。本文最后會給出代碼的下載地址,可以從代碼中獲取jar包。首先看看最簡單的用法,單個類解析 看以下的json數據。
~~~
{name:"mike",age:18}
~~~
通過解析以上的json串來熟悉下gson的用法。因為以上是一個JSONObject,首先我們先定義一個Model類。
~~~
public class Easy {
public String name;
public int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
~~~
然后接上來的就很簡單了,看如下代碼:
~~~
Easy easy = new Gson().fromJson(json,Easy.class );
~~~
其中json就是要解析的字符串,到此就完成了解析,相當方便。那如果是對象里嵌套對象呢,也很簡單,只要修改下Model文件。如解析如下數據:
~~~
{name:"mike",age:18{name:tank}}
~~~
只需把model改成如下:
~~~
public class Easy {
public String name;
public int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public class child{
public String name;
</span>public String getName() {
return name;
}
~~~
~~~
public void setName(String name) {
this.name = name;
}
~~~
接下來我們來看看JSONArray的解析。解析如下json數據:
~~~
[{name:"mike",age:11},{name:"alan",age:15}]
~~~
以上是一個JSONArray,解析方式如下:
~~~
Type type = new TypeToken<ArrayList<Easy>>(){}.getType();
ArrayList<Easy> list = new Gson().fromJson(new MyJsonParse().arrayParse(), type);
~~~
這樣解析后的數據就存在數組list中。簡單的用法介紹完了,接下來介紹復雜點的json解析。
### 二,復雜的gson解析
接下來來嘗試解析下豆瓣api讀書的json數據。
~~~
{"category":{
"@scheme":"http://www.douban.com/2007#kind",
"@term":"http://www.douban.com/2007#book"},
"db:tag":[
{"@count":20,"@name":"片山恭一"},
{"@count":14,"@name":"日本"},
{"@count":10,"@name":"小說"},
{"@count":8,"@name":"日本文學"},
{"@count":4,"@name":"愛情"}
],
"title":{"$t":"滿月之夜白鯨現"},
"author":[
{"name":{"$t":"(日)片山恭一"}}
],
"summary":{"$t":"冷靜地想一想吧!公寓的一個房間里只有兩上人,連被褥都鋪
好了,理應是犯錯誤的時候,我為什么卻這么拘謹?一直膽小的毛病又犯了。事到
如今,不要說上床,就連接吻也還差得很遠。這就是橫亙在男人和女人之間的又深
又暗的河流嗎?\n 如果有可能,我希望把手伸進她的心里,把她內心所有的東
西都掏出來。她對我究竟是一種什么感覺呢?我在她的心昊確實占有一席之地嗎?
抑或只是她生命中的匆匆過客?"},
"link":[
{"@rel":"self","@href":"http://api.douban.com/book/subject/1220562"},
{"@rel":"alternate","@href":"http://book.douban.com/subject/1220562/"},
{"@rel":"image","@href":"http://img3.douban.com/spic/s1747553.jpg"}
],
"db:attribute":[
{"$t":"(日)片山恭一","@name":"author"},
{"$t":"7543632608","@name":"isbn10"},
{"$t":"9787543632608","@name":"isbn13"},
{"$t":"180","@name":"pages"},
{"$t":"豫人","@name":"tranlator"},
{"$t":"18.00","@name":"price"},
{"$t":"青島出版社","@name":"publisher"},
{"$t":"平裝(無盤)","@name":"binding"},
{"$t":"片山恭一,1959年生于日本愛媛縣,九州大學農學系農業經濟學專業
畢業。學生時代通讀了包括夏目漱石和大江健三郎在內的日本近現代文學全集,
同時讀了笛卡爾、萊布尼茨到結構主義的歐洲近現代哲學。也讀了馬克思。
學士論文寫的是馬克思,碩士論文寫的是恩格斯。二十二三歲開始創作小說。
代表作有《在世界中心呼喚愛》、《世界在你不知道的地方運轉》、《氣息》、
《別相信約翰·列儂》、《滿月之夜白鯨現》、《空鏡頭》以及新作《倘若我在
彼岸》、《雨天的海豚們》等。","@name":"author-intro"}
],
"id":{"$t":"http://api.douban.com/book/subject/1220562"},
"gd:rating":{"@min":1,"@numRaters":39,"@average":"3.69","@max":5}
}
~~~
以上json格式比較復雜。如果你不需要全部讀取,只需讀取一部分,比如讀取內容,可以用以下方式。先定義內容的Model類
~~~
public class Content {
String $t;
public void set$t(String $t) {
this.$t = $t;
}
public String get$t() {
return $t;
}
}
~~~
再對其進行讀取
~~~
Gson gson = new Gson();
JsonElement element = new JsonParser().parse(json);
JsonObject object = element.getAsJsonObject();
JsonElement cElement = object.get("summary");
Content c = gson.fromJson(cElement, Content.class);
~~~
這樣就把summary的類讀取了出來。不用全部讀。那如果要把所有內容都讀取出來呢。我們來實現下以下的功能。讀取相關信息并顯示如下的界面。

難點在于Model類的編寫。Model的編寫是按照json格式來的。如下:
~~~
public class BookInfo {
private categories category;
@SerializedName(" db:tag")
private List<tag> db;
private Title title;
private List<Author> author;
private Content summary;
private List<link> link;
@SerializedName(" db:attribute")
public List<attribute> attributes;
public Id id;
@SerializedName(" db:rating")
public rating rating;
public void setCategory(categories category) {
this.category = category;
}
public void setDb(List<tag> db) {
this.db = db;
}
public void setTitle(Title title) {
this.title = title;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
public void setContent(Content content) {
this.summary = content;
}
public void setLink(List<BookInfo.link> link) {
this.link = link;
}
public void setAttributes(List<attribute> attributes) {
this.attributes = attributes;
}
public void setId(Id id) {
this.id = id;
}
public void setRating(BookInfo.rating rating) {
this.rating = rating;
}
public categories getCategory() {
return category;
}
public List<tag> getDb() {
return db;
}
public Title getTitle() {
return title;
}
public List<Author> getAuthor() {
return author;
}
public Content getContent() {
return summary;
}
public List<BookInfo.link> getLink() {
return link;
}
public List<attribute> getAttributes() {
return attributes;
}
public Id getId() {
return id;
}
public BookInfo.rating getRating() {
return rating;
}
public class categories{
@SerializedName("@scheme")
public String scheme;
@SerializedName("@term")
public String term;
public void setScheme(String scheme) {
this.scheme = scheme;
}
public void setTerm(String term) {
this.term = term;
}
public String getScheme() {
return scheme;
}
public String getTerm() {
return term;
}
}
public class tag{
@SerializedName("@count")
public String count;
@SerializedName("@name")
public String name;
public void setCount(String count) {
this.count = count;
}
public void setName(String name) {
this.name = name;
}
public String getCount() {
return count;
}
public String getName() {
return name;
}
}
public class Title{
@SerializedName("$t")
private String title;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public class Author{
private Name name;
public void setName(Name name) {
this.name = name;
}
public Name getName() {
return name;
}
}
public class Name{
@SerializedName("$t")
public String authorName;
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getAuthorName() {
return authorName;
}
}
public class Content{
@SerializedName("$t")
public String content;
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
public class link{
@SerializedName("@rel")
public String lrel;
@SerializedName("@href")
public String lhref;
public void setLrel(String lrel) {
this.lrel = lrel;
}
public String getLrel() {
return lrel;
}
public void setLhref(String lhref) {
this.lhref = lhref;
}
public String getLhref() {
return lhref;
}
}
public class attribute{
public List<myAttribute> myAttribute;
public void setMyAttribute(List<BookInfo.myAttribute> myAttribute) {
this.myAttribute = myAttribute;
}
public List<BookInfo.myAttribute> getMyAttribute() {
return myAttribute;
}
}
public class myAttribute{
@SerializedName("$t")
public String aRel;
@SerializedName("@name")
public String aNname;
public void setaRel(String aRel) {
this.aRel = aRel;
}
public void setaNname(String aNname) {
this.aNname = aNname;
}
public String getaRel() {
return aRel;
}
public String getaNname() {
return aNname;
}
}
public class Id{
@SerializedName("$t")
public String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
public class rating{
@SerializedName("@min")
public int min;
@SerializedName("@numRaters")
public int numRaters;
@SerializedName("@average")
public String average;
public int getMax() {
return max;
}
public int getMin() {
return min;
}
public int getNumRaters() {
return numRaters;
}
public String getAverage() {
return average;
}
public void setMin(int min) {
this.min = min;
}
public void setNumRaters(int numRaters) {
this.numRaters = numRaters;
}
public void setAverage(String average) {
this.average = average;
}
public void setMax(int max) {
this.max = max;
}
@SerializedName("@max")
public int max;
}
}
~~~
本來變量名都要定義成與json中名一樣,但因為此json數據很多名稱如@rel并不適合當變量名,所以使用注解@serizalName來轉化名字,這樣只要保持@serizalName后的名稱與json數據中名稱一致就可以,Model類中的變量名可以自己起。以上代碼有點長,我們就挑圖片url獲取為例子,其它以此類推。
~~~
"link":[
{"@rel":"self","@href":"http://api.douban.com/book/subject/1220562"},
{"@rel":"alternate","@href":"http://book.douban.com/subject/1220562/"},
{"@rel":"image","@href":"http://img3.douban.com/spic/s1747553.jpg"}
],
~~~
如上,我們要獲取第三個。因為link里是一個數組,數組里有三個object,所以其定義為
~~~
<pre name="code" class="java">private List<link> link;<span style="font-family: Arial, Helvetica, sans-serif;"> ?</span>
~~~
~~~
public class link{
@SerializedName("@rel")
public String lrel;
@SerializedName("@href")
public String lhref;
public void setLrel(String lrel) {
this.lrel = lrel;
}
public String getLrel() {
return lrel;
}
public void setLhref(String lhref) {
this.lhref = lhref;
}
public String getLhref() {
return lhref;
}
}
~~~
首先因為是數組,所以link應該定義成List,而link類是我們自己起的類,其中有兩個屬性,分別對應json中的兩個屬性。這樣就定義完成。接下來很簡單了。調用gson來進行解析,代碼如下:
~~~
Gson gson = new Gson();
BookInfo info = gson.fromJson(json, BookInfo.class);
~~~
~~~
BookInfo info = new MyJsonParse().parseInfoBook(msg.obj.toString());
bookTitle.setText(info.getTitle().getTitle());
bookAuthor.setText(info.getAuthor().get(0).getName().getAuthorName());
bookAbstract.setText(info.getContent().getContent());
Picasso.with(BookDetailActivity.this).load(info.getLink().get(2).getLhref()).placeholder(R.drawable.book_head).error(R.drawable.book_head).into(bookPic);
~~~
這樣就把數據解析出來了。
gson的出現給我們讀取json數據帶來很大的方便,應該好好的使用它。附上代碼的下載地址。
[github下載地址](https://github.com/reallin/GsonPrase.git)
- 前言
- Android底部tab與標題欄相結合
- Android免費獲取短信驗證碼
- android中Handler的源碼分析
- 詳解Fragment的傳值問題
- 詳談gson解析
- android新控件之toolbar,floatingActionButton,SnackBar,CollapsingToolbarLayout
- android自定義控件
- 淺談android的線程池
- Android的消息處理機制,AsyncTask源碼解析
- IPC——android進程間通信
- CoCos2d_android入門所需知道的一切
- Cocos2d_android你所需要知道的一切(下)
- Activity你需要知道的一切
- Activity啟動過程源碼分析
- Data Binding Guide——google官方文檔翻譯(上)
- Data Binding Guide——google官方文檔翻譯(下)
- android TextView實現跑馬燈效果
- android中生成excel
- Volley源碼解析
- LayoutInflater源碼解析
- android發送郵件
- android測試工具MonkeyRunner--google官網翻譯
- android View繪制源碼分析
- Android中Window添加View的底層原理
- 仿美團商品選購下拉菜單實現