編輯:關於 Android 程式設計
上一篇我們用 Android 原生的 JSONObject 手寫解析,能跑,但字段一多就寫得手酸。做久了會發現,成熟的第三方解析庫確實能省下大量時間。這次我們不再拆成兩篇,直接把目前最主流的 Gson 與 Fastjson 放在同一份數據上跑一遍,最後再聊聊取捨。
這兩套庫背後都是大廠:一個來自 Google 官方,一個出自阿里巴巴工程師之手。以下介紹綜合了官方文檔與社區資料。
Google 提供的 Java 類庫,負責在 Java 對象與 JSON 文本之間雙向映射——既能把 JSON 字符串還原成對象,也能把對象序列化回 JSON。
主要優點:解析快、開銷小;調用方式面向對象,代碼量極少;數據傳輸與解析都很順手。
由阿里巴巴工程師用 Java 實現的高性能 JSON 解析器與生成器,官方宣稱在當時的 Java JSON 庫中性能領先。
主要優點:速度極快;面向對象;支持普通 JDK 類、任意 JavaBean、Collection、Map、Date、Enum 等類型;零依賴(有 JDK 就能跑);支持注解與全類型序列化。
Gson 的用法很直白:先定義實體類,再讓它幫你轉。
API 文檔:https://sites.google.com/site/gson/
Jar 下載:https://github.com/google/gson
本文示例同時用到 Gson 和 Volley,記得把兩個架包都放進項目;另外別忘了加網絡權限:
<uses-permission android:name="android.permission.INTERNET" />
接口選用豆瓣的圖書接口,返回的 JSON 大致如下:
{
"rating": { "max": 10, "numRaters": 351, "average": "7.0", "min": 0 },
"subtitle": "",
"author": [ "[日] 片山恭一" ],
"pubdate": "2005-1",
"tags": [
{ "count": 139, "name": "片山恭一", "title": "片山恭一" },
{ "count": 66, "name": "日本", "title": "日本" },
{ "count": 62, "name": "日本文學", "title": "日本文學" }
],
"image": "https://img3.doubanio.com/mpic/s1747553.jpg",
"binding": "平裝",
"translator": [ "豫人" ],
"pages": "180",
"images": {
"small": "https://img3.doubanio.com/spic/s1747553.jpg",
"large": "https://img3.doubanio.com/lpic/s1747553.jpg",
"medium": "https://img3.doubanio.com/mpic/s1747553.jpg"
},
"id": "1220562",
"publisher": "青島出版社",
"isbn10": "7543632608",
"isbn13": "9787543632608",
"title": "滿月之夜白鯨現",
"url": "https://api.douban.com/v2/book/1220562",
"summary": "那一年,是聽莫扎特、釣鱸魚和家庭破裂的一年……",
"price": "15.00元"
}
仔細看其實結構並不複雜:一個對象裡嵌了若干字段,其中 tags 是對象數組。先把數據拉回來再說。

private void getJson() {
StringRequest request = new StringRequest(url,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.i("json", s);
Volley_json(s);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) { }
});
// 加入 Volley 請求隊列
new Volley().newRequestQueue(getApplicationContext()).add(request);
}
拿到字符串之後定義實體類。注意成員變量名要與 JSON 的 key 完全一致。
public class Book {
private String title; // 書名
private String publisher; // 出版社
private String summary; // 簡介
private ArrayList<Tag> tags; // 標簽數組
// 省略 getter / setter
}
public class Tag {
private String count;
private String name;
private String title;
// 省略 getter / setter
}
實體準備好之後,解析只需要一行:
private void Volley_json(String json) {
Gson gson = new Gson();
Book book = gson.fromJson(json, Book.class);
tv_content.setText("書名:" + book.getTitle() + "\n"
+ "出版社:" + book.getPublisher() + "\n"
+ "簡介:" + book.getSummary() + "\n"
+ "標簽數:" + book.getTags().size() + "\n");
}

幾個容易踩的坑:
1、內部嵌套的類必須聲明為 static,否則解析會出錯;
2、類裡的屬性名必須和 JSON 的 key 一模一樣;
3、用 [] 括起來的部分是數組,聲明成 public List<B> b;只用 {} 嵌套的則聲明成 public C c。
好在現在 Android Studio 已經有 GsonFormat 這類插件,照着 JSON 就能直接生成實體類,更加省事。
Github:https://github.com/alibaba/fastjson/releases
下載架包之後,前面的實體類與 Volley 請求都不用改,差別只在解析那一行:
private void Volley_json(String json) {
Book book = JSON.parseObject(json, Book.class);
tv_content.setText("書名:" + book.getTitle() + "\n"
+ "出版社:" + book.getPublisher() + "\n"
+ "簡介:" + book.getSummary() + "\n"
+ "標簽數:" + book.getTags().size() + "\n");
}

API 風格幾乎一致,替換成本很低——這也是為什麼很多項目能在兩個庫之間近乎無痛切換。
接口這次依舊從聚合數據找免費 API。

接口地址(示例,需替換為自己的 KEY):https://apis.juhe.cn/goodbook/catalog?key=你的KEY&dtype=json
{
"resultcode": "200",
"reason": "success",
"result": [
{ "id": "242", "catalog": "中國文學" },
{ "id": "252", "catalog": "人物傳記" },
{ "id": "244", "catalog": "兒童文學" },
{ "id": "248", "catalog": "歷史" },
{ "id": "257", "catalog": "哲學" },
{ "id": "243", "catalog": "外國文學" },
{ "id": "247", "catalog": "小說" }
],
"error_code": 0
}
結構很簡單:外層是狀態字段,裡面 result 是一個數組。按部就班,先用 Volley 取數據。
界面部分只放一個 ListView,item 只用一個 TextView,所以實體類也非常輕量:
public class BookListBean {
private String id; // 分類 ID
private String catalog; // 分類名稱
// 省略 getter / setter
}
適配器用 ViewHolder 複用 convertView:
public class BookListAdapter extends BaseAdapter {
private Context mContext;
private List<BookListBean> mList;
private LayoutInflater mInflater;
public BookListAdapter(Context context, List<BookListBean> list) {
this.mContext = context;
this.mList = list;
mInflater = LayoutInflater.from(context);
}
@Override public int getCount() { return mList.size(); }
@Override public Object getItem(int position) { return mList.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.mTextView = convertView.findViewById(R.id.mTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BookListBean bean = mList.get(position);
holder.mTextView.setText(bean.getId() + "\n" + bean.getCatalog());
return convertView;
}
static class ViewHolder {
TextView mTextView;
}
}
解析時要留意:result 對應的是一個列表,Gson 需要借助 TypeToken 告訴它目標類型。
private void Volley_json(String json) throws JSONException {
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<BookListBean>>() {}.getType();
JSONObject object = new JSONObject(json);
ArrayList<BookListBean> list = gson.fromJson(object.getString("result"), listType);
adapter = new BookListAdapter(this, list);
mListView.setAdapter(adapter);
}

至此,兩個庫的基本用法和一個完整的列表案例都跑通了。本文刻意停留在入門層面,沒有深入性能壓測與自定義序列化,後續有機會再寫一篇進階的。
Android 遊戲開發之碰撞偵測(矩形、圓形、像素)
碰撞偵測是幾乎所有遊戲都離不開的核心機制。本文整理 Android 遊戲開發中常見的幾種碰撞偵測方式,並附上可直接套用的程式碼。 矩形碰撞 原理:判斷兩個矩形的位置關係
Android 入門第一課:點擊按鈕改變文字顏色
這是一個再適合不過的 Android 入門小範例:畫面上有一行文字和三顆按鈕,點綠、藍、黃按鈕,文字就會變成對應的顏色。透過它,你能快速熟悉版面配置、控制項初始化與事件監
Android 官方導航欄 ActionBar 使用詳解
一、ActionBar 概述ActionBar 是 Android 3.0 以後新增的元件,主要用於標示應用程式以及用戶所處的位置,並提供相關操作與全局導航功能。真正使用
java/android 設計模式學習筆記(15)——責任鏈模式
這篇博客我們來介紹責任鏈模式(Chain-of-responsibility Pattern),它又稱職責鏈模式,是行為型設計模式之一。顧名思義,責任鏈模式中存在一個鏈式