Android-解析JSON資料(JSON物件/JSON陣列)
在上一篇部落格中,Android-封裝JSON資料(JSON物件/JSON陣列),講解到Android真實開發中更多的是去解析JSON資料(JSON物件/JSON陣列)
封裝JSON的資料是在伺服器端進行封裝了,Android更多的工作是解析(JSON物件/JSON陣列),所以Android開發JSON資料的解析非常重要
JSON資料,是儲存在檔案裡面:
/data/data/liudeli.mynetwork01/files/pottingJSON1
{ "name":"李四", "age":99, "hobby":"愛好是練習截拳道" }
/data/data/liudeli.mynetwork01/files/pottingJSON2
{
"student":{
"name":"李四",
"age":99,
"hobby":"愛好是練習截拳道"
}
}
/data/data/liudeli.mynetwork01/files/pottingJSON3
{ "student":{ "name":"李四", "age":99, "hobby":"愛好是練習截拳道", "dog":{ "name":"阿黃", "age":77, "sex":"母" } } }
/data/data/liudeli.mynetwork01/files/pottingJSONArray1
[
{
"name":"君君",
"age":89,
"sex":"男"
},
{
"name":"小君",
"age":99,
"sex":"女"
},
{
"name":"大君",
"age":88,
"sex":"男"
}
]
/data/data/liudeli.mynetwork01/files/pottingJSONArray2
{
"person":[
{
"name":"君君",
"age":89,
"sex":"男"
},
{
"name":"小君",
"age":99,
"sex":"女"
},
{
"name":"大君",
"age":88,
"sex":"男"
}
]
}
為什麼要使用jsonObject.optString, 不使用jsonObject.getString
因為jsonObject.optString獲取null不會報錯
看著JSON資料,一步一步的解析就好了,當明白JSON資料格式後,解析是非常容易的:
AnalyzeJSONActivity.java
package liudeli.mynetwork01; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import org.json.JSONArray; import org.json.JSONObject; import java.io.InputStream; public class AnalyzeJSONActivity extends Activity { private final String TAG = AnalyzeJSONActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_analyze_json); } /** * 解析JSON物件 * { * "name":"李四", * "age":99, * "hobby":"愛好是練習截拳道" * } * @param view */ public void analyzeJSON1(View view) { String result = readFile("pottingJSON1"); // Log.d(TAG, "result:" + result); try{ JSONObject jsonObject = new JSONObject(result); /** * 為什麼要使用jsonObject.optString, 不使用jsonObject.getString * 因為jsonObject.optString獲取null不會報錯 */ String name = jsonObject.optString("name", null); int age = jsonObject.optInt("age", 0); String hobby = jsonObject.optString("hobby", null); // 日誌列印結果: Log.d(TAG, "analyzeJSON1解析的結果:name:" + name + " age:" + age + " hobby:" + hobby); } catch (Exception e) { e.printStackTrace(); } } /** * 解析JSON物件-帶Key * { * "student":{ * "name":"李四", * "age":99, * "hobby":"愛好是練習截拳道" * } * } * @param view */ public void analyzeJSON2(View view) { String result = readFile("pottingJSON2"); // Log.d(TAG, "result:" + result); try{ // 整個最大的JSON物件 JSONObject jsonObjectALL = new JSONObject(result); /** * 為什麼要使用jsonObject.optString, 不使用jsonObject.getString * 因為jsonObject.optString獲取null不會報錯 */ String student = jsonObjectALL.optString("student", null); if (!TextUtils.isEmpty(student)) { JSONObject jsonObject = new JSONObject(student); String name = jsonObject.optString("name", null); int age = jsonObject.optInt("age", 0); String hobby = jsonObject.optString("hobby", null); // 日誌列印結果: Log.d(TAG, "analyzeJSON2解析的結果:name:" + name + " age:" + age + " hobby:" + hobby); } } catch (Exception e) { e.printStackTrace(); } } /** * 解析JSON物件-巢狀物件 * { * "student":{ * "name":"李四", * "age":99, * "hobby":"愛好是練習截拳道", * "dog":{ * "name":"阿黃", * "age":77, * "sex":"母" * } * } * } * @param view */ public void analyzeJSON3(View view) { String result = readFile("pottingJSON3"); // Log.d(TAG, "result:" + result); try{ // 整個最大的JSON物件 JSONObject jsonObjectALL = new JSONObject(result); /** * 為什麼要使用jsonObject.optString, 不使用jsonObject.getString * 因為jsonObject.optString獲取null不會報錯 */ String student = jsonObjectALL.optString("student", null); if (!TextUtils.isEmpty(student)) { JSONObject jsonObject = new JSONObject(student); String name = jsonObject.optString("name", null); int age = jsonObject.optInt("age", 0); String hobby = jsonObject.optString("hobby", null); // 以下是dog JSON 物件相關的解析 String dogStr = jsonObject.optString("dog", null); // 定義dog的JSON物件 JSONObject dogJSONObject = new JSONObject(dogStr); String dogName = dogJSONObject.optString("name", null); int dogAge = dogJSONObject.optInt("age", 0); String dogSex = dogJSONObject.optString("sex", null); // 日誌列印結果: Log.d(TAG, "analyzeJSON3解析的結果:name:" + name + " age:" + age + " hobby:" + hobby + "\n" + "dogName:" + dogName + " dogAge:" + dogAge + " dogSex:" + dogSex); } } catch (Exception e) { e.printStackTrace(); } } /** * 解析JSON陣列 * [ * { * "name":"君君", * "age":89, * "sex":"男" * }, * { * "name":"小君", * "age":99, * "sex":"女" * }, * { * "name":"大君", * "age":88, * "sex":"男" * } * ] * @param view */ public void analyzeJSONArray1(View view) { String result = readFile("pottingJSONArray1"); // Log.d(TAG, "result:" + result); try{ // 整個最大的JSON陣列 JSONArray jsonArray = new JSONArray(result); Log.d(TAG, "analyzeJSONArray1 jsonArray:" + jsonArray); // [{"name":"君君","age":89,"sex":"男"},{"name":"小君","age":99,"sex":"女"},{"name":"大君","age":88,"sex":"男"}] for (int i = 0; i < jsonArray.length(); i++) { // JSON數組裡面的具體-JSON物件 JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.optString("name", null); int age = jsonObject.optInt("age", 0); String sex = jsonObject.optString("sex", null); // 日誌列印結果: Log.d(TAG, "analyzeJSONArray1 解析的結果:name" + name + " age:" + age + " sex:" + sex); } } catch (Exception e) { e.printStackTrace(); } } /** * 解析JSON陣列-帶Key * { * "person":[ * { * "name":"君君", * "age":89, * "sex":"男" * }, * { * "name":"小君", * "age":99, * "sex":"女" * }, * { * "name":"大君", * "age":88, * "sex":"男" * } * ] * } * @param view */ public void analyzeJSONArray2(View view) { String result = readFile("pottingJSONArray2"); // Log.d(TAG, "result:" + result); try{ /** * JSON陣列在牛逼,一旦有了 key person 這樣的標記,就必須先是個 JSON物件 * 最外層的JSON物件,最大的哪個 { ... } */ JSONObject jsonObjectALL = new JSONObject(result); // 通過標識(person),獲取JSON陣列 JSONArray jsonArray = jsonObjectALL.getJSONArray("person"); Log.d(TAG, "analyzeJSONArray1 jsonArray:" + jsonArray); // [{"name":"君君","age":89,"sex":"男"},{"name":"小君","age":99,"sex":"女"},{"name":"大君","age":88,"sex":"男"}] for (int i = 0; i < jsonArray.length(); i++) { // JSON數組裡面的具體-JSON物件 JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.optString("name", null); int age = jsonObject.optInt("age", 0); String sex = jsonObject.optString("sex", null); // 日誌列印結果: Log.d(TAG, "analyzeJSONArray2 解析的結果:name" + name + " age:" + age + " sex:" + sex); } } catch (Exception e) { e.printStackTrace(); } } /** * 讀取檔案裡面的字串 * @param fileName * @return */ private String readFile(String fileName) { String result = null; try { InputStream inputStream = openFileInput(fileName); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); result = new String(bytes); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 定義一個Bean */ /*class Student { private String name; private int age; private String hobby; public Student(String name, int age, String hobby) { this.name = name; this.age = age; this.hobby = hobby; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", hobby='" + hobby + '\'' + '}'; } }*/ }
activity_analyze_json.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解析JSON物件" android:onClick="analyzeJSON1" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解析JSON物件-帶Key" android:onClick="analyzeJSON2" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解析JSON物件-巢狀物件" android:onClick="analyzeJSON3" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解析JSON陣列" android:onClick="analyzeJSONArray1" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解析JSON陣列-帶Key" android:onClick="analyzeJSONArray2" android:layout_weight="1" /> </LinearLayout> </LinearLayout>
所有解析JSON的Log列印:
analyzeJSON1
12-23 21:46:44.127 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSON1解析的結果:name:李四 age:99 hobby:愛好是練習截拳道
analyzeJSON2
12-23 21:46:59.161 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSON2解析的結果:name:李四 age:99 hobby:愛好是練習截拳道
analyzeJSON3
12-23 21:47:12.240 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSON3解析的結果:name:李四 age:99 hobby:愛好是練習截拳道
dogName:阿黃 dogAge:77 dogSex:母
analyzeJSONArray1
12-23 21:47:35.108 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSONArray1 解析的結果:name君君 age:89 sex:男
12-23 21:47:35.108 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSONArray1 解析的結果:name小君 age:99 sex:女
12-23 21:47:35.108 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSONArray1 解析的結果:name大君 age:88 sex:男
analyzeJSONArray2
12-23 21:47:55.457 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSONArray2 解析的結果:name君君 age:89 sex:男
12-23 21:47:55.457 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSONArray2 解析的結果:name小君 age:99 sex:女
12-23 21:47:55.457 8204-8204/liudeli.mynetwork01 D/AnalyzeJSONActivity: analyzeJSONArray2 解析的結果:name大君 age:88 sex:男