android 讀取JSON數據(遍歷JSONObject和JSONArray) .

private String getJson() {
		//jsonString中含有比如unicode編碼字符\u67ef的話,getString時自動會轉化爲相應語言字符。
		//從服務器獲取的數據片段一般爲以下格式
		/*{"showid":"38f5ef6ae35711e0a046",
			"showname":"\u996d\u5c40\u4e5f\u75af\u72c2",
			"completed":1,
			"paid":1,
			"releasedate":"2012-01-23",
			"episode_total":"1",
			"episode_last":"1",
			"show_thumburl":"http:\/\/g4.ykimg.com\/0102641F464F04034A000000000000E09BC52F-62AE-3FA1-E4F0-A62472C09DC0",
			"showcreatetime":"2011-09-20 15:07:37",
			"showcategory":"\u7535\u5f71",
			"deschead":"\u4f20\u8bf4\u4e2d\u7684\u201c\u5929\u4eba\u4e00\u201d\u996d\u9986\uff0c\u6d77\u9c9c\u8d29\u5b50\u8001\u867e\u7c73\u524d\u6765\u5411\u6b63\u8d70\u9709\u8fd0\u7684\u5c01\u8001\u677f\u8ba8\u503a\u3002\u4e0e\u6b64\u540c\u65f6\uff0c\u7edd\u8272\u6027\u611f\u7684\u7f8e\u5973\uff0c\u795e\u79d8\u5a01\u4e25\u7684\u5927\u4eba\u7269\uff0c\u8fc7\u6c14\u7684\u529f\u592b\u660e\u661f\uff0c\u56fd\u5b66\u5927\u5e08\uff0c\u66b4\u53d1\u6237,
			\u6d41\u6d6a\u6b4c\u624b\uff0c\u5a01\u4e25\u7684...",
			"showtotal_comment":"583",
			"reputation":"8.335",
			"showtotal_vv":"2952956",
			"show_vthumburl":"http:\/\/g3.ykimg.com\/0102641F464F10C6CF0000000000001078AA2C-3507-7A46-AC81-15FBCEC1A241",
			"movie_genre":["\u559c\u5267",
			"\u5267\u60c5"],
			"area":["\u5927\u9646"],
			"performer":[{"id":"12657",
			"name":"\u5218\u6866",
			"character":["\u5c01\u8001\u677f"]},
			{"id":"14685",
			"name":"\u8303\u4f1f",
			"character":["\u8c2d\u5927\u5e08"]},
			{"id":"186154",
			"name":"\u9ec4\u6e24",
			"character":["\u5bb6\u660e"]},
			{"id":"21889",
			"name":"\u83ab\u5c0f\u68cb",
			"character":["\u83ab\u59ae\u5361"]},
			{"id":"17725",
			"name":"\u4ee3\u4e50\u4e50",
			"character":["\u5c0f\u8774\u8776"]},
			{"id":"15808",
			"name":"\u6881\u51a0\u534e",
			"character":["\u8001\u6885"]},
			{"id":"17853",
			"name":"\u97e9\u7ae5\u751f",
			"character":["\u5927\u8001\u603b"]},
			{"id":"16635",
			"name":"\u5218\u4e9a\u6d25",
			"character":["\u8521\u7259\u91d1"]},
			{"id":"161699",
			"name":"\u51af\u74c5",
			"character":["\u72d7\u72d7"]},
			{"id":"228705",
			"name":"\u5df4\u591a",
			"character":["\u8001\u867e\u7c73"]}],
			"firstepisode_videourl":"http:\/\/v.youku.com\/v_show\/id_XMzU4MTA3Mjc2.html",
			"showlink":"http:\/\/www.youku.com\/show_page\/id_z38f5ef6ae35711e0a046.html",
			"quality":"\u8d85\u6e05"},*/
		String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";
		try {
			Log.d("debugTest","jsonString -- "+jsonString);
			JSONObject result = new JSONObject(jsonString);//轉換爲JSONObject
//			int num = result.length();
			JSONArray nameList = result.getJSONArray("name");//獲取JSONArray
			int length = nameList.length();
			String aa = "";
			for(int i = 0; i < length; i++) {//遍歷JSONArray
				
				JSONObject oj = nameList.getJSONObject(i);
				aa = aa + oj.getString("name")+"|";
				Log.d("debugTest",Integer.toString(i)+"  aa-- "+aa);
			}
			Iterator<?> it = result.keys();
			String aa2 = "";
			String bb2 = null;
			while(it.hasNext()){//遍歷JSONObject
				bb2 = (String) it.next().toString();
				aa2 = aa2 + result.getString(bb2);
				Log.d("debugTest",bb2+" -- "+aa2);
			}
			Log.d("debugTest","aa2 -- "+aa2);
			return aa;
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
		/*LOG結果:
		D/debugTest( 4291): jsonString -- {"FLAG":"flag","MESSAGE":"SUCCESS","name":[{"name":"jack"},{"name":"lucy"}]}
		D/debugTest( 4291): 0  aa-- jack|
		D/debugTest( 4291): 1  aa-- jack|lucy|
		D/debugTest( 4291): FLAG -- flag
		D/debugTest( 4291): MESSAGE -- flagSUCCESS
		D/debugTest( 4291): name -- flagSUCCESS[{"name":"jack"},{"name":"lucy"}]
		D/debugTest( 4291): aa2 -- flagSUCCESS[{"name":"jack"},{"name":"lucy"}]*/

	}


 

JSON的定義:

一種輕量級的數據交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術爲其提供了完整的解決方案(有點類似於正則表達式 ,獲得了當今大部分語言的支持),從而可以在不同平臺間進行數據交換。JSON採用兼容性很高的文本格式,同時也具備類似於C語言體系的行爲。 – Json.org

爲什麼用JSON?

很簡單,因爲它比xml快十倍。

有哪些應用案例?

Twitter、豆瓣、facebook等公司的開放api,一般這些服務都會提供多種格式供開發人員選擇(xml、json、atom等),而在手機終端上,我們自然希望給用戶最佳體驗,所以我選用最有效率的json格式。

按照我的文檔習慣,將會附上具體demo,在本文檔末尾中可找到下載,其中的示例是用豆瓣api。

JSON的結構:

Name/Value Pairs            類似所熟知的Keyed list、Hash table、Disctionary和Associative array。在Android平臺中同時存在另外一個類“Bundle”,某種程度上具有相似的行爲。
org.json.JSONObject    Array,一組有序的數據列表。org.json.JSONArray

Android中 JSON相關的類(4個)和Exceptions(1個):

l  JSONArray

l  JSONObject

l  JSONStringer

l  JSONTokener

l  JSONException

JSONObject:

這是系統中有關JSON定義的基本單元,其包含一對兒(Key/Value)數值。它對外部(External:應用toString()方法輸出的數值) 調用的響應體現爲一個標準的字符串(例如:{"JSON": "Hello, World"},最外被大括號包裹,其中的Key和Value被冒號":"分隔)。其對於內部(Internal)行爲的操作格式略微,例如:初始化一個 JSONObject實例,引用內部的put()方法添加數值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之間是以逗號","分隔。

Value的類型包括:Boolean、JSONArray、 JSONObject、Number、String或者默認值JSONObject.NULL object。

有兩個不同的取值方法:

get(): 在確定數值存在的條件下使用,否則當無法檢索到相關Key時,將會拋出一個Exception信息。

opt(): 這個方法相對比較靈活,當無法獲取所指定數值時,將會返回一個默認數值,並不會拋出異常。

JSONArray:

它代表一組有序的數值。將其轉換爲String輸出(toString)所表現的形式是用方括號包裹,數值以逗號”,”分隔(例如: [value1,value2,value3],大家可以親自利用簡短的代碼更加直觀的瞭解其格式)。這個類的內部同樣具有查詢行爲,get()和 opt()兩種方法都可以通過index索引返回指定的數值,put()方法用來添加或者替換數值。

同樣這個類的value類型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默認值JSONObject.NULL object。

JSONStringer:

根據官方的解釋,這個類可以幫助快速和便捷的創建JSON text。其最大的優點在於可以減少由於格式的錯誤導致程序異常,引用這個類可以自動嚴格按照JSON語法規則(syntax rules)創建JSON text。每個JSONStringer實體只能對應創建一個JSON text。

根據下邊的實例來了解其它相關信息: string myString = new JSONStringer().object()

.key("AR").value("www.Androidres.com!")

.endObject()

.toString();

複製代碼結果是一組標準格式的JSON text:{”AR”:”www.Androidres.com!”}

其中的.object() 和.endObject()必須同時使用,是爲了按照Object標準給數值添加邊界。同樣,針對數組也有一組標準的方法來生成邊界.array() 和.endArray()。

JSONTokener:

這個是系統爲JSONObject和JSONArray構造器解析 JSON source string的類,它可以從source string中提取數值信息。

JSONException:

是 JSON.org類拋出的異常信息。

一個好用的工具JsonViewer

Json的數據格式可讀性較差,但是藉助這個工具,可以清晰看出它的數據結構。

官方地址 http://jsonviewer.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=5432

讀取Json數據
public String getJson(){
        String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack \"},{\"name\":\"lucy\"}]}";//json字符串
        try {
            JSONObject result = new JSONObject(jsonstring);//轉換爲JSONObject
            int num = result.length();
            JSONArray nameList = result.getJSONArray("name");//獲取JSONArray
            int length = nameList.length();
            String aa = "";
            for(int i = 0; i < length; i++){//遍歷JSONArray
                Log.d("debugTest",Integer.toString(i));
                JSONObject oj = nameList.getJSONObject(i);
                aa = aa + oj.getString("name")+"|";
                
            }
            Iterator<?> it = result.keys();
            String aa2 = "";
            String bb2 = null;
            while(it.hasNext()){//遍歷JSONObject
                bb2 = (String) it.next().toString();
                aa2 = aa2 + result.getString(bb2);
                
            }
            return aa;
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章