Android json數據解析

前言

喜歡在前言裡講一下自己的現狀,或許能有共鳴的同學,更多的是留給自己一個紀念,幾個月或者幾年再回來看的時候還是會很有感慨。今天說說語言,json這種數據格式之前我做服務器端的時候天天接觸,天真的以為json的世界裡隻有php的json_encode和json_decode,今天當我做客戶端的時候,竟然將近一個多小時才搞定json的解析。這裡我不是抨擊php好壞,隻是想說多學點東西,看看你不熟悉的領域,方能開闊自己的視野,方能知道天外有天,方能知道當初你看不上的工作其實你也不一定能很好的完成,扯多瞭,回來講解json

什麼是json

json(Javascript Object Natation)是一種輕量級的數據交換格式,相比xml這種數據交換格式來說,json相對解析更加簡單一些,因此客戶端和服務器的數據交換格式往往通過json進行交換

json一共有兩種數據結構,一種是以(key/value)對形式存在的無序的jsonObject對象,一個對象以“{”(左花括號)開始,“}”(右花括號)結束。每個“名稱”後跟一個“:”(冒號); “名稱/值”對之間使用“,”(逗號)

例如:{”name“:”zhengyi.wzy”},這就是一個最簡單的json對象,對於這種數據格式,key值必須是String,而value則可以是String,Number,Object,Array等數據類型

另一種數據格式就是有序的value的集合,這種形式被稱為是jsonArray,數組是值(value)的有序集合。一個數組以”[“(左中括號)開始,”]“(右中括號)結束。值之間使用”,“(逗號)分隔

vc/B6bvuo6y1sc7et6i78cihy/nWuLaoyv0mIzIwNTQwO8qxo6y9q7vht7W72NK7uPbErMjPJiMyMDU0MDujrLKisru74cXXs/bS7LOjo6i49sjLzca89sq508PV4rj2t723qKOpCjxicj4KCgo8aDM+SlNPTkFycmF5PC9oMz4Ky/y0+rHt0rvX6dPQ0PK1xMr9JiMyMDU0MDuho72rxuTXqru7zqpTdHJpbmfK5LP2KHRvU3RyaW5nKcv5se3P1rXE0M7KvcrH08O3vcCousWw/Ln8o6zK/SYjMjA1NDA70tS2urrFobEsobG31rj0o6jA/cjno7pbobFBbGliYWJhobAsobFCYWlkdaGwLKGwVGVjZW50obFdo6kKPGJyPgoK1eK49sDgtcTE2rK/zazR+b7f09Cy6dGv0NDOqqOsZ2V0KCm6zW9wdCgpwb3W1re9t6i2vL/J0tTNqLn9aW5kZXjL99L9t7W72Na4tqi1xMr9JiMyMDU0MDujrHB1dCgpt723qNPDwLTM7bzTu/LV38zmu7vK/SYjMjA1NDA7Cjxicj4KzazR+UpTT05BcnJhebXEdmFsdWXA4NDNv8nS1LD8wKijukpTT05PYmplY3RzLCBKU09OQXJyYXlzLCBTdHJpbmdzLCBCb29sZWFucywgSW50ZWdlcnMsIExvbmdzLCBEb3VibGVzIG9yIE5VTEw8YnI+Cgo8YnI+Cgo8YnI+Cgo8aDI+QW5kcm9pZL3izvbKtcD9PC9oMj4Kv827p7bL0ruw47TTt/7O8cb3u/G1w7a8ysfX1rf7tK6jrNaxvdNuZXfSu7j2SlNPTk9iamVjdLy0v8mjrLLOv7yzzNDyyOfPwgo8YnI+Cgo8aDM+u/HIoWpzb27X1rf7tK48L2gzPgrV4rj2zfjWt8zhuanBy2pzb27X1rf7tK6jumh0dHA6Ly9hcGkuYW5kcm9pZGhpdmUuaW5mby9jb250YWN0cy+jrCDO0sPHv8nS1L+qxvTSu7j2z9+zzLeixvBodHRwx+vH86Osu/HIoWpzb27X1rf7tK6jrLLOv7y0+sLryOfPwqO6Cjxicj4KCjxwcmUgY2xhc3M9″brush:java;”>private String getJsonByNetwork() {
// You can get json by this url
final String url = “https://api.androidhive.info/contacts/”;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);

InputStream inputStream = null;
String result = null;

try {
HttpResponse response = httpClient.execute(httpGet);
inputStream = response.getEntity().getContent();

// Json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, “UTF-8”));
StringBuilder sb = new StringBuilder();
String tmp = null;

while ((tmp = reader.readLine()) != null) {
sb.append(tmp);
}

result = sb.toString();
} catch (Exception e) {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException se) {
}
}

return result;
}

解析json字符串

解析json字符串的步驟一般如下所示:

(1) 創建JSONObject:

// Create a JSONObject
JSONObject jsonObject = new JSONObject(result);

(2) 獲取JSONArray,遍歷JSONArray數組

// To get a specific JSONArray
JSONArray jsonArray = jsonObject.getJSONArray("contacts");

// To get items from the array
for (int i = 0; i < jsonArray.length(); i ++) {
    // TODO:Traverse the jsonarray
}

(3) 獲取JSONObject

// Create a JSONObject
JSONObject jsonObject = new JSONObject(result);

// To get a specific JSONArray
JSONArray jsonArray = jsonObject.getJSONArray("contacts");

// To get items from the array
for (int i = 0; i < jsonArray.length(); i++) {
	// To get a specific JSONObject
	JSONObject oneObject = jsonArray.getJSONObject(i);
}

(4)獲取特定字符串

// Create a JSONObject
JSONObject jsonObject = new JSONObject(result);

// To get a specific JSONArray
JSONArray jsonArray = jsonObject.getJSONArray("contacts");

// To get items from the array
for (int i = 0; i < jsonArray.length(); i++) {
	// To get a specific JSONObject
	JSONObject oneObject = jsonArray.getJSONObject(i);

	// To get a specific string
	String id = oneObject.getString("id");
	String name = oneObject.getString("name");

	Log.e("wzy", "id is:" + id + ", name is " + name);
}

解析結果:

03-05 10:26:08.690: E/wzy(26401): id is:c200, name is Ravi Tamada
03-05 10:26:08.690: E/wzy(26401): id is:c201, name is Johnny Depp
03-05 10:26:08.690: E/wzy(26401): id is:c202, name is Leonardo Dicaprio
03-05 10:26:08.690: E/wzy(26401): id is:c203, name is John Wayne
03-05 10:26:08.691: E/wzy(26401): id is:c204, name is Angelina Jolie
03-05 10:26:08.691: E/wzy(26401): id is:c205, name is Dido
03-05 10:26:08.691: E/wzy(26401): id is:c206, name is Adele
03-05 10:26:08.692: E/wzy(26401): id is:c207, name is Hugh Jackman
03-05 10:26:08.693: E/wzy(26401): id is:c208, name is Will Smith
03-05 10:26:08.693: E/wzy(26401): id is:c209, name is Clint Eastwood
03-05 10:26:08.694: E/wzy(26401): id is:c2010, name is Barack Obama
03-05 10:26:08.694: E/wzy(26401): id is:c2011, name is Kate Winslet
03-05 10:26:08.695: E/wzy(26401): id is:c2012, name is Eminem

發佈留言