轉載自http://www.sojson.com/in.html
1 JSON是什麼?
JSON
是什麼?百度百科是這麼解釋的。
JSON(JavaScript Object Notation)
是一種輕量級的數據交換格式。它基於ECMAScript的一個子集。 JSON採用完全獨立於語言的文本格式,但是也使用了類似於C語言家族的習慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。這些特性使JSON成爲理想的數據交換語言。 易於人閱讀和編寫,同時也易於機器解析和生成(一般用於提升網絡傳輸速率)。
爲了不和時代落伍,我們必須要學習 XML 和 JSON,但同時它們也很容易學習。也可以加入我們的JSON大軍:QQ羣:259217951
XML很好很強大,但是最近有另外一個時代弄潮兒,這就是JSON。現在JSON的光環已經逐漸超越了XML,各大網站提供的數據接口一般都是JSON。下面我們就來學習下JSON。
2 JSON格式
JSON構建於兩種結構:
“名稱/值”對的集合(A collection of name/value pairs)。不同的語言中,它被理解爲對象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組(associative array)。
值的有序列表(An ordered list of values)。在大多數語言中,它被理解爲數組(array)、矢量(vector), 列表(list)或者是序列(sequence)。
JSON具有以下這些形式:
對象是一個無序的“’名稱/值’對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。
數組是值(value)的有序集合。一個數組以“[”(左中括號)開始,“]”(右中括號)結束。值之間使用“,”(逗號)分隔。
數字(number)類似C或者Java裏面的數,沒有用到的8進制和16進制數除外。
字符串(string)是由0到多個Unicode字符組成的序列,封裝在雙引號(”“)中, 可以使用反斜槓(‘\’)來進行轉義。一個字符可以表示爲一個單一字符的字符串。
值(value)可以是雙引號括起來的字符串(string)、數值(number)、true、false、 null、對象(object)或者數組(array)。這些結構可以嵌套。
3 舉個栗子
上面關於JSON講了這麼多,大家都表示一頭霧水了吧?
沒關係,我們來舉個栗子,讓大家有個直觀的感受:–)
以目前視頻使用的iQiyi提供的頻道接口爲例:
iQiyi提供的電影頻道的JSON電影數據如下:
{"code": 1, "data": 0, "albumIdList": [ { "totalidnum": 2000, "idlist": [ "319281600" ] } ], "albumArray": { "319281600": { "_as": "", "_blk": 0, "_cid": 1, "_ct": "2014-10-10 17:55:06", "_da": "", "_dl": 0, "_dn": "7296", "_id": 319281600, "_img": "http://pic2.qiyipic.com/p_w_picpath/20141016/19/ca/v_108628048_m_601_m1_120_160.jpg", "_ip": 1, "_ma": "", "_pc": 2, "_pid": 0, "_reseftv": 959, "_t": "末代獨裁", "_tvct": 1, "_tvs": 1, "_vt": 0, "a_av": 1, "a_pro": "", "bpt": "0", "clm": "", "cn_year": "0", "co_album_id": "0", "ctype": 0, "desc": "", "down": 0, "down2": "0", "drm": 0, "fst_time": "2014-10-16", "h1_img": "http://pic2.qiyipic.com/p_w_picpath/20141016/19/ca/v_108628048_m_601_m1_180_236.jpg", "h2_img": "http://pic2.qiyipic.com/p_w_picpath/20141016/19/ca/v_108628048_m_601_m1_195_260.jpg", "is_h": 0, "is_n": 0, "is_zb": 0, "k_word": "", "language": 0, "live_center": 0, "live_start_time": 0, "live_stop_time": 0, "logo": 1, "m_av": 1, "p_av": 1, "p_s": 0, "p_s_1": 0, "p_s_4": 0, "p_s_8": 0, "qiyi_pro": 0, "qiyi_year": "0", "qt_id": "1005722", "s_TT": "", "songname": "", "t_pc": 1, "tag": "當代 美國 鄉村 大片", "tv_eftv": 1, "tv_pha": "", "tv_pro": "", "tv_ss": "", "tvfcs": "雄心壯志背後的真相", "up": 0, "up2": "0", "upcl": "", "v2_img": "http://pic2.qiyipic.com/p_w_picpath/20141016/19/ca/v_108628048_m_601_m1_284_160.jpg", "v3_img": "http://pic2.qiyipic.com/p_w_picpath/20141016/19/ca/v_108628048_m_601_m1_480_270.jpg", "vv": "1", "year": "2007", "tv_id": "0", "vv_p": 0, "vv_f": 2, "vv_m": 0, "_sc": 8 } }, "changeAlbum": null, "category": null, "before": "2~4~1~7~3", "latest_push_id": "655", "up_tm": "1413441370874", "recommend_attach": "", "preset_keys": null, "category_group": null, "exp_ts": 120, "stfile_path": "/data/view/online5/0/1/2.1.8.5.1.txt"}
從上面的例子可以很清晰的看出JSON是如何展示一個電影的數據的,當然這是JSON格式化之後的數據。JSON的元數據是不便於閱讀的。
4 如何解析JSON?
Android JSON所有相關類,都在org.json包下。
包括JSONObject、JSONArray、JSONStringer、JSONTokener、JSONWriter、JSONException。
<1>. 常見方法
目前JSON解析有2種方法,分別是get和opt方法,可以使用JSON
那麼使用get方法與使用opt方法的區別是?
JsonObject方法,opt與get建議使用opt方法,因爲get方法如果其內容爲空會直接拋出異常。不過JsonArray.opt(index)會有越界問題需要特別注意。
opt、optBoolean、optDouble、optInt、optLong、optString、optJSONArray、optJSONObject get、getBoolean、getDouble、getInt、getLong、getString、getJSONArray、getJSONObject
<2>. Android中如何創建JSON?
在Android中應該如何創建JSON呢?
下面展示了一個如何創建JSON的例子:
private String createJson() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("intKey", 123); jsonObject.put("doubleKey", 10.1); jsonObject.put("longKey", 666666666); jsonObject.put("stringKey", "lalala"); jsonObject.put("booleanKey", true); JSONArray jsonArray = new JSONArray(); jsonArray.put(0, 111); jsonArray.put("second"); jsonObject.put("arrayKey", jsonArray); JSONObject innerJsonObject = new JSONObject(); innerJsonObject.put("innerStr", "inner"); jsonObject.put("innerObjectKey", innerJsonObject); Log.e("Json", jsonObject.toString()); return jsonObject.toString();}
其輸出結果如下所示(JSON格式化後的結果):
{ "intKey": 123, "doubleKey": 10.1, "longKey": 666666666, "stringKey": "lalala", "booleanKey": true, "arrayKey": [ 111, "second" ], "innerObjectKey": { "innerStr": "inner" }}
<3>. 如何解析JSON?
下面以視頻中解析iQiyi的每個視頻album數據爲例來說明如何解析JSON:
第一步,需要從網絡服務器上發起請求,獲取到JSON數據:
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { MyLog.d(TAG, "response=" + response); parseiQiyiInterfaceResponse(response); } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { /* * if (error instanceof NetworkError) { } else if (error * instanceof ClientError) { } else if (error instanceof * ServerError) { } else if (error instanceof * AuthFailureError) { } else if (error instanceof * ParseError) { } else if (error instanceof * NoConnectionError) { } else if (error instanceof * TimeoutError) { } */ MyLog.e(TAG, "onErrorResponse, error=" + error); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("t", iQiyiInterface.getEncryptTimestamp()); headers.put("sign", iQiyiInterface.getSign()); return headers; }};
第二步,獲取到對應的對應的JSONObject數據:
public void getJsonObjectString(String url) { mQueue = VideoApplication.getInstance().getRequestQueue(); JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { MyLog.e(TAG, "response = " + response.toString()); JSONArray jsonArray = null; JSONObject jsonObject = null; try { jsonObject = response.getJSONObject("response"); jsonArray = jsonObject.getJSONObject("result").getJSONArray("album"); } catch (JSONException e) { e.printStackTrace(); } if (jsonArray == null) { return; } mChannelList = VideoUtils.parseVideoJsonArray(jsonArray); if (isLoading) { isLoading = false; if (mIsGrid) { mChannelGridAdapter.appendChannelVideoInfo(mChannelList); } else { mChannelListAdapter.appendChannelVideoInfo(mChannelList); } } else { if (mIsGrid) { mChannelGridAdapter.setChannelVideoInfo(mChannelList); showOppoGrid(); } else { mChannelListAdapter.setChannelVideoInfo(mChannelList); showOppoList(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { MyLog.e(TAG, "error = " + error); } }); jsObjRequest.setTag(TAG); jsObjRequest.setShouldCache(true); mQueue.add(jsObjRequest); mQueue.start();}
獲取到JSON Object之後,就對這個JSONObject進行解析:
private ArrayList parseVideoAlbumJsonObject(JSONObject albumJSONObject, ArrayList albumIdJSONArrayList) { MyLog.d(TAG, "parseVideoAlbumJsonObject, length=" + albumJSONObject.length()); if (albumJSONObject.length() < 1) { return null; } ArrayList<VideoConstant> videos = new ArrayList<VideoConstant>(); try { for (int index = 0; index < albumJSONObject.length(); index++) { VideoConstant video = new VideoConstant(); JSONObject itemJsonObject; itemJsonObject = albumJSONObject.getJSONObject(albumIdJSONArrayList.get(index) .toString()); MyLog.d(TAG, "string=" + albumIdJSONArrayList.get(index).toString()); video.mAlbumId = itemJsonObject.optString(InterfaceParameterName.ID); video.mAtitle = itemJsonObject.optString(InterfaceParameterName.TITLE); video.mEpisodeCount = itemJsonObject.optString(InterfaceParameterName.UPDATE_SET); video.mTvSets = itemJsonObject.optString(InterfaceParameterName.TV_SETS); video.mDesc = itemJsonObject.optString(InterfaceParameterName.DESCRIPTION); video.mCid = itemJsonObject.optString(InterfaceParameterName.CATEGORY_ID); video.mImg = itemJsonObject.optString(InterfaceParameterName.IMG); video.mHighimg = itemJsonObject .optString(InterfaceParameterName.HIGH_RESO_PORT_IMG); video.mHoriImg = itemJsonObject .optString(InterfaceParameterName.HIGH_RESO_HORI_IMG); video.mScore = itemJsonObject.optString(InterfaceParameterName.SCORE); video.mMainActors = itemJsonObject.optString(InterfaceParameterName.MAIN_ACTOR); video.mCreateTime = itemJsonObject.optString(InterfaceParameterName.CREATE_TIME); video.mDuration = itemJsonObject.optString(InterfaceParameterName.DURATION); video.mTag = itemJsonObject.optString(InterfaceParameterName.TAG); MyLog.d(TAG, "id=" + video.mAlbumId + ",title=" + video.mAlbumTitle + ",img=" + video.mHighimg + ",tvsets=" + video.mTvSets); videos.add(video); } } catch (JSONException e) { e.printStackTrace(); } return videos;}
<4>. Android JSON解析庫
上面介紹都是使用Android提供的原生類解析JSON,最大的好處是項目不需要引入第三方庫,但是如果比較注重開發效率而且不在意應用大小增加幾百K的話,有以下JSON可供選擇:
大家可以去對應的官網下載並學習
三、 JSON vs. XML
JSON和XML就像武林界的屠龍刀和倚天劍,那麼他們孰強孰弱?
XML長期執數據傳輸界之牛耳,而JSON作爲後起之秀,已經盟主發起了挑戰。
那就讓他們來進行PK一下:
<1>. JSON相比XML的不同之處
沒有結束標籤
更短
讀寫的速度更快
能夠使用內建的 JavaScript eval() 方法進行解析
使用數組
不使用保留字
總之: JSON 比 XML 更小、更快,更易解析。
<2>. XML和JSON的區別:
XML的主要組成成分:
XML是element、attribute和element content。
JSON的主要組成成分:
JSON是object、array、string、number、boolean(true/false)和null。
XML要表示一個object(指name-value pair的集合),最初可能會使用element作爲object,每個key-value pair 用 attribute 表示:
<student name="soゝso" age="27"/>
但如個某個 value 也是 object,那麼就不可以當作attribute:
<student name="soゝso" age="27"> <address> <country>中國</country> <province>北京市</province> <city>朝陽區</city> <district>北京市朝陽區東四環遠洋國際中心A座1906 </district> </address></student>
那麼,什麼時候用element,什麼時候用attribute,就已經是一個問題了。
而JSON因爲有object這種類型,可以自然地映射,不需考慮上述的問題,自然地得到以下的格式。
{ "name": "John", "age" : 10, "address" : { "country" : "中國", "province" : "北京市", "city" : "朝陽區", "district" : "北京市朝陽區東四環遠洋國際中心A座1906", }}
One More Thing…
XML需要選擇怎麼處理element content的換行,而JSON string則不須作這個選擇。
XML只有文字,沒有預設的數字格式,而JSON則有明確的number格式,這樣在locale上也安全。
XML映射數組沒大問題,就是數組元素tag比較重複冗餘。JSON 比較易讀。
JSON的true/false/null也能容易統一至一般編程語言的對應語義。
XML文檔可以附上DTD、Schema,還有一堆的諸如XPath之類規範,使用自定義XML元素或屬性,能很方便地給數據附加各種約束條件和關聯額外信息,從數據表達能力上看,XML強於Json,但是很多場景並不需要這麼複雜的重量級的東西,輕便靈活的Json就顯得很受歡迎了。
打個比方,如果完成某件事有兩種方式:一種簡單的,一個複雜的。你選哪個?
JSON與XML相比就是這樣的。
這篇文章只是對XML和JSON這2種目前主流使用的數據格式進行了解釋,並系統的學習了其中的語法及如何進行解析,同時在最好針對XML和JSON做了對比,瞭解其不同點和各自的優勢。
期望有需要的朋友有所幫助。
轉載請註明出處:http://www.sojson.com/in.html