在開發過程中,我們常常需要解析 JSON 數據。尤其在移動端開發中,復雜的 JSON 數據結構和嵌套層次較多是很常見的。
下面我們通過一個具體的例子來演示如何解析復雜 JSON 數據:
{ "code": 200, "data": { "page": 1, "pageSize": 10, "total": 1000, "list": [ { "id": 1, "name": "張三", "age": 18, "gender": "male", "phone": "13888888888", "email": "zhangsan@qq.com", "address": { "province": "廣東", "city": "深圳", "district": "福田" }, "score": [ { "subject": "語文", "score": 80 }, { "subject": "數學", "score": 90 }, ] }, { "id": 2, "name": "李四", "age": 20, "gender": "female", "phone": "13999999999", "email": "lisi@qq.com", "address": { "province": "廣東", "city": "廣州", "district": "天河" }, "score": [ { "subject": "語文", "score": 85 }, { "subject": "數學", "score": 95 }, ] }, ] } }
我們可以通過以下代碼來解析這份 JSON 數據:
try { JSONObject jsonObject = new JSONObject(jsonData); int code = jsonObject.getInt("code"); JSONObject data = jsonObject.getJSONObject("data"); int page = data.getInt("page"); int pageSize = data.getInt("pageSize"); int total = data.getInt("total"); JSONArray list = data.getJSONArray("list"); for (int i = 0; i< list.length(); i++) { JSONObject item = list.getJSONObject(i); int id = item.getInt("id"); String name = item.getString("name"); int age = item.getInt("age"); String gender = item.getString("gender"); String phone = item.getString("phone"); String email = item.getString("email"); JSONObject address = item.getJSONObject("address"); String province = address.getString("province"); String city = address.getString("city"); String district = address.getString("district"); JSONArray score = item.getJSONArray("score"); for (int j = 0; j< score.length(); j++) { JSONObject subItem = score.getJSONObject(j); String subject = subItem.getString("subject"); int scoreValue = subItem.getInt("score"); // TODO 處理數據 } } } catch (JSONException e) { e.printStackTrace(); }
通過以上代碼,我們可以成功解析出整個 JSON 數據,并且取出其中的數據,進行處理。但需要注意的是:如果 JSON 數據結構過于復雜,我們需要耐心和細心,仔細檢查每個嵌套層次的數據格式和命名。只有做到充分理解數據結構和分析數據規律,才能完成復雜 JSON 解析工作。
上一篇mysql中空
下一篇Mysql中磁盤頁是什么