如今的APP很少有不跟服務器打交道的,其中在輕量級的通信交互中,JSON(JavaScript Object Notation)和XML,並稱為客戶端和服務端交互解決方案的倚天劍和屠龍刀,本文主要介紹JSON相關的知識。
JSON中對象包括在一對大括號裡面,對象中的每一個item都是一個"key:value"數據對,數據對之間以逗號來分隔。JSON對象的key只能是String類型,value可能是其它類型如number,boolean,null。如下所示
{ "Name" : "Alex", "Sex" : "Male", "Age" : "20",}
JSON數組包括在一對中括號裡面,每一個元素都是一個JSON對象,也是以逗號來分隔,示例如下
[ { "Name" : "Alex", "Sex" : "Male", "Age" : "20", }, { "Name" : "May", "Sex" : "Female", "Age" : "19", }, { "Name" : "Mike", "Sex" : "Male", "Age" : "21", }]
FastJSON是alibaba公司開發出來的專門解析JSON的一個框架,根據他們自己的測試,速度非常快,效率非常高,而且沒有之一。我們以從聚合數據網站上查詢蘇州城市天氣預報的一個JSON數據為例來說明,獲取的URL地址是http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=6f9276e4d79c5d102bbfb28717beba93。為確保數據源沒有問題,可以在浏覽器中打開URL,看看是否有數據。這裡再介紹一款Mac下的工具JSON Accelerator,不但可以從網絡上抓取,還可以添加http請求頭信息,使用起來非常方便。
新建工程取名為FastJSONDemo,由於要訪問網絡,所以需要在AndroidManifest.xml中添加相應權限
<uses-permission android:name="android.permission.INTERNET" />
網絡請求部分,這裡我們使用volley這個庫,Google出品,使用簡單。源碼下載地址https://android.googlesource.com/platform/frameworks/volley/,jar包的下載地址http://download.csdn.net/detail/djstava/8793421。下載後把volley的庫導入到工程中,UI的話,用了一個TextView來顯示接收到的json數據
為了建立一個全局的請求隊列,需要在實現一個繼承自Application的子類,叫VolleyApplication
package com.djstava.fastjsondemo;import android.app.Application;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;/*** 包名稱: com.djstava.fastjsondemo* 創建人: djstava* 創建時間: 15/9/23 下午3:44*/public class VolleyApplication extends Application{ public static RequestQueue requestQueue; @Override public void onCreate() { super.onCreate(); requestQueue = Volley.newRequestQueue(getApplicationContext());}public static RequestQueue getVolleyQueue() { return requestQueue; }}
然後在MainActivity中的onStart方法編寫請求部分,然後在onStop方法中取消請求
private static final String JSON_URL = "http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=6f9276e4d79c5d102bbfb28717beba93";//字段key是從聚合數據網站上申請過來的,請自行替換@Overrideprotected void onStart() { super.onStart(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { try { textView.setText(jsonObject.toString()); Log.e(TAG,"result:" + jsonObject.getString("resultcode")); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e(TAG, volleyError.getMessage()); } }); jsonObjectRequest.setTag("fastjson"); VolleyApplication.requestQueue.add(jsonObjectRequest);}@Overrideprotected void onStop() { super.onStop(); VolleyApplication.requestQueue.cancelAll("fastjson");}
別忘了在AndroiManifest.xml文件Application標簽中加入
android:name=".VolleyApplication"
使用Genymotion模擬器運行程序,可以看到獲取的數據
為了方便讀者查看,利用JSON Accelerator格式化一下
{"result" : {"sk" : { "humidity" : "58%", "wind_direction" : "西北風", "temp" : "26", "wind_strength" : "2級", "time" : "17:27"},"today" : { "temperature" : "22℃~27℃", "dressing_index" : "舒適", "dressing_advice" : "建議著長袖T恤、襯衫加單褲等服裝。年老體弱者宜著針織長袖襯衫、馬甲和長褲。", "uv_index" : "弱", "comfort_index" : "", "wind" : "東北風3-4 級", "weather" : "多雲轉陣雨", "city" : "蘇州", "date_y" : "2015年09月24日", "week" : "星期四", "wash_index" : "不宜", "weather_id" : { "fa" : "01", "fb" : "03" }, "travel_index" : "較適宜", "exercise_index" : "較適宜", "drying_index" : ""},"future" : [ { "temperature" : "22℃~27℃", "weather_id" : { "fa" : "01", "fb" : "03" }, "wind" : "東北風3-4 級", "week" : "星期四", "date" : "20150924", "weather" : "多雲轉陣雨" }, { "temperature" : "21℃~26℃", "weather_id" : { "fa" : "03", "fb" : "01" }, "wind" : "東北風3-4 級", "week" : "星期五", "date" : "20150925", "weather" : "陣雨轉多雲" }, { "temperature" : "21℃~27℃", "weather_id" : { "fa" : "01", "fb" : "01" }, "wind" : "東北風3-4 級", "week" : "星期六", "date" : "20150926", "weather" : "多雲" }, { "temperature" : "21℃~28℃", "weather_id" : { "fa" : "00", "fb" : "00" }, "wind" : "東北風3-4 級", "week" : "星期日", "date" : "20150927", "weather" : "晴" }, { "temperature" : "22℃~28℃", "weather_id" : { "fa" : "01", "fb" : "01" }, "wind" : "東風3-4 級", "week" : "星期一", "date" : "20150928", "weather" : "多雲" }, { "temperature" : "22℃~28℃", "weather_id" : { "fa" : "01", "fb" : "03" }, "wind" : "東風3-4 級", "week" : "星期二", "date" : "20150929", "weather" : "多雲轉陣雨" }, { "temperature" : "20℃~25℃", "weather_id" : { "fa" : "04", "fb" : "04" }, "wind" : "東南風4-5 級", "week" : "星期三", "date" : "20150930", "weather" : "雷陣雨" } ] }, "resultcode" : "200", "reason" : "successed!", "error_code" : 0}
接下來該輪到fastjson登場了,,先到http://repo1.maven.org/maven2/com/alibaba/fastjson/下載對應版本的jar包,或者到https://github.com/alibaba/fastjson下載源碼,再導入到工程中。
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { try { textView.setText(jsonObject.toString()); com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(jsonObject.toString()); for (Map.Entry<String, Object> entry : jsonObject1.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e(TAG, volleyError.getMessage()); } });
這樣,簡單的數據解析就完成了。
JavaBean是符合某種規范的java組件,也就是java類,它必須滿足如下特性:
我們把公司員工抽象成一個類,然後利用fastjson來解析
package com.djstava.fastjsondemo;/** * 包名稱: com.djstava.fastjsondemo * 創建人: djstava * 創建時間: 15/9/28 上午11:07 */public class Employee { private int num; private String name; private int age; public Employee(int num, String name, int age) { this.num = num; this.name = name; this.age = age; } public void setNum(int num) { this.num = num; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public int getNum() { return num; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Employee{" + "num=" + num + ", name='" + name + '\'' + ", age=" + age + '}'; }}
在Android Studio中,可以自動生成get、set、toString這些方法,Code->Generate,快捷鍵是Command + N。
Employee employee = new Employee(1,"djstava",20);Log.e(TAG,JSON.toJSONString(employee));
可以看出輸出的json格式與我們類中定義的屬性的順序不一致,其實沒有關系,json都是通過key去獲取其對應的value的。
如果僅僅是想解析JavaBean類中某幾個字段時,可以使用SimplePropertyPreFilter這個類來實現,將需要解析的字段添加進來,如將Employee類中的"num"和"name"解析出來
SimplePropertyPreFilter simplePropertyPreFilter = new SimplePropertyPreFilter(Employee.class,"num","name");Log.e(TAG,JSON.toJSONString(employee,simplePropertyPreFilter));
http://download.csdn.net/detail/djstavav/9144789
1、http://www.json.org/
2、https://github.com/alibaba/fastjson/wiki
3、https://www.juhe.cn/docs/api/id/39