JSON是什么?百度百科是這么解釋的。
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式。它基于ECMAScript的一個(gè)子集。 JSON采用完全獨(dú)立于語言的文本格式,但是也使用了類似于C語言家族的習(xí)慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。這些特性使JSON成為理想的數(shù)據(jù)交換語言。 易于人閱讀和編寫,同時(shí)也易于機(jī)器解析和生成(一般用于提升網(wǎng)絡(luò)傳輸速率)。
為了不和時(shí)代落伍,我們必須要學(xué)習(xí) XML 和 JSON,但同時(shí)它們也很容易學(xué)習(xí)。也可以加入我們的JSON大軍:QQ群:259217951
XML很好很強(qiáng)大,但是最近有另外一個(gè)時(shí)代弄潮兒,這就是JSON?,F(xiàn)在JSON的光環(huán)已經(jīng)逐漸超越了XML,各大網(wǎng)站提供的數(shù)據(jù)接口一般都是JSON。下面我們就來學(xué)習(xí)下JSON。




上面關(guān)于JSON講了這么多,大家都表示一頭霧水了吧?
沒關(guān)系,我們來舉個(gè)栗子,讓大家有個(gè)直觀的感受:–)
以目前視頻使用的iQiyi提供的頻道接口為例:
{"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/image/20141016/19/ca/v_108628048_m_601_m1_120_160.jpg",
"_ip": 1,
"_ma": "",
"_pc": 2,
"_pid": 0,
"_reseftv": 959,
"_t": "末代獨(dú)裁",
"_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/image/20141016/19/ca/v_108628048_m_601_m1_180_236.jpg",
"h2_img": "http://pic2.qiyipic.com/image/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": "當(dāng)代 美國(guó) 鄉(xiāng)村 大片",
"tv_eftv": 1,
"tv_pha": "",
"tv_pro": "",
"tv_ss": "",
"tvfcs": "雄心壯志背后的真相",
"up": 0,
"up2": "0",
"upcl": "",
"v2_img": "http://pic2.qiyipic.com/image/20141016/19/ca/v_108628048_m_601_m1_284_160.jpg",
"v3_img": "http://pic2.qiyipic.com/image/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"
}
Android JSON所有相關(guān)類,都在org.json包下。
包括JSONObject、JSONArray、JSONStringer、JSONTokener、JSONWriter、JSONException。
目前JSON解析有2種方法,分別是get和opt方法,可以使用JSON
那么使用get方法與使用opt方法的區(qū)別是?
JsonObject方法,opt與get建議使用opt方法,因?yàn)?strong>get方法如果其內(nèi)容為空會(huì)直接拋出異常。不過JsonArray.opt(index)會(huì)有越界問題需要特別注意。
opt、optBoolean、optDouble、optInt、optLong、optString、optJSONArray、optJSONObject get、getBoolean、getDouble、getInt、getLong、getString、getJSONArray、getJSONObject
在Android中應(yīng)該如何創(chuàng)建JSON呢?
下面展示了一個(gè)如何創(chuàng)建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();
}
其輸出結(jié)果如下所示(JSON格式化后的結(jié)果):
{
"intKey": 123,
"doubleKey": 10.1,
"longKey": 666666666,
"stringKey": "lalala",
"booleanKey": true,
"arrayKey": [
111,
"second"
],
"innerObjectKey": {
"innerStr": "inner"
}
}
下面以視頻中解析iQiyi的每個(gè)視頻album數(shù)據(jù)為例來說明如何解析JSON:
第一步,需要從網(wǎng)絡(luò)服務(wù)器上發(fā)起請(qǐng)求,獲取到JSON數(shù)據(jù):
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;
}
};
第二步,獲取到對(duì)應(yīng)的對(duì)應(yīng)的JSONObject數(shù)據(jù):
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之后,就對(duì)這個(gè)JSONObject進(jìn)行解析:
private ArrayListparseVideoAlbumJsonObject(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; }
上面介紹都是使用Android提供的原生類解析JSON,最大的好處是項(xiàng)目不需要引入第三方庫(kù),但是如果比較注重開發(fā)效率而且不在意應(yīng)用大小增加幾百K的話,有以下JSON可供選擇:
大家可以去對(duì)應(yīng)的官網(wǎng)下載并學(xué)習(xí)
JSON和XML就像武林界的屠龍刀和倚天劍,那么他們孰強(qiáng)孰弱?
XML長(zhǎng)期執(zhí)數(shù)據(jù)傳輸界之牛耳,而JSON作為后起之秀,已經(jīng)盟主發(fā)起了挑戰(zhàn)。
那就讓他們來進(jìn)行PK一下:
總之: JSON 比 XML 更小、更快,更易解析。
XML的主要組成成分:
XML是element、attribute和element content。
JSON的主要組成成分:
JSON是object、array、string、number、boolean(true/false)和null。
XML要表示一個(gè)object(指name-value pair的集合),最初可能會(huì)使用element作為object,每個(gè)key-value pair 用 attribute 表示:
<student name="soゝso" age="27"/>
但如個(gè)某個(gè) value 也是 object,那么就不可以當(dāng)作attribute:
<student name="soゝso" age="27">
<address>
<country>中國(guó)</country>
<province>北京市</province>
<city>朝陽區(qū)</city>
<district>北京市朝陽區(qū)東四環(huán)遠(yuǎn)洋國(guó)際中心A座1906 </district>
</address>
</student>
那么,什么時(shí)候用element,什么時(shí)候用attribute,就已經(jīng)是一個(gè)問題了。
而JSON因?yàn)橛衞bject這種類型,可以自然地映射,不需考慮上述的問題,自然地得到以下的格式。
{
"name": "John",
"age" : 10,
"address" : {
"country" : "中國(guó)",
"province" : "北京市",
"city" : "朝陽區(qū)",
"district" : "北京市朝陽區(qū)東四環(huán)遠(yuǎn)洋國(guó)際中心A座1906",
}
}
One More Thing…
XML需要選擇怎么處理element content的換行,而JSON string則不須作這個(gè)選擇。
XML只有文字,沒有預(yù)設(shè)的數(shù)字格式,而JSON則有明確的number格式,這樣在locale上也安全。
XML映射數(shù)組沒大問題,就是數(shù)組元素tag比較重復(fù)冗余。JSON 比較易讀。
JSON的true/false/null也能容易統(tǒng)一至一般編程語言的對(duì)應(yīng)語義。
XML文檔可以附上DTD、Schema,還有一堆的諸如XPath之類規(guī)范,使用自定義XML元素或?qū)傩?,能很方便地給數(shù)據(jù)附加各種約束條件和關(guān)聯(lián)額外信息,從數(shù)據(jù)表達(dá)能力上看,XML強(qiáng)于Json,但是很多場(chǎng)景并不需要這么復(fù)雜的重量級(jí)的東西,輕便靈活的Json就顯得很受歡迎了。
打個(gè)比方,如果完成某件事有兩種方式:一種簡(jiǎn)單的,一個(gè)復(fù)雜的。你選哪個(gè)?
JSON與XML相比就是這樣的。
這篇文章只是對(duì)XML和JSON這2種目前主流使用的數(shù)據(jù)格式進(jìn)行了解釋,并系統(tǒng)的學(xué)習(xí)了其中的語法及如何進(jìn)行解析,同時(shí)在最好針對(duì)XML和JSON做了對(duì)比,了解其不同點(diǎn)和各自的優(yōu)勢(shì)。
期望有需要的朋友有所幫助。
轉(zhuǎn)載請(qǐng)注明出處:http://suancuo.cn/in.html