Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 原生 JSON 解析的三個層次:JSONObject、JSONArray 與多層巢狀

編輯:關於 Android 程式設計

最近專案裡要做一个天氣預覽頁,欄位多、資料層級也深,索性整理成一篇筆記,對自己複習、對讀者也有幫助。

另外提醒:只要涉及網路,記得先在 AndroidManifest 加上權限,這步永遠不會錯。

<!-- 網路權限 -->
<uses-permission android:name="android.permission.INTERNET" />

一、單層結構:JSONObject(以手機號碼歸屬地為例)

先用號碼歸屬地查詢當暖身題。範例接口:

https://apis.juhe.cn/mobile/get?phone=18679606764&key=你的key

以下三個範例都會用 Volley 抓取接口並取得 JSON 字串,不熟 Volley 的人建議先補一下基礎。
專案地址:https://github.com/adamrocker/volley

/** 抓取接口 */
private void Volley_Get() {
    String url = "https://apis.juhe.cn/mobile/get?phone=" + myPhone + "&key=你的key";
    RequestQueue queue = Volley.newRequestQueue(this);
    StringRequest request = new StringRequest(Method.PUBLIC, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                Log.i("Json", json);
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError errorLog) {
                Log.e("Error", errorLog.toString());
            }
        });
    queue.add(request);
}

這樣就拿到一 Trace JSON 字串了:

{
    "error_code": 0,
    "reason": "Return Successd!",
    "result": {
        "areacode": "0796",
        "card": "江西聯通GSM卡",
        "city": "吉安",
        "company": "中國聯通",
        "province": "江西",
        "zip": "343000"
    },
    "resultcode": "200"
}

結構很清楚:最外層是一對大括號,裡頭是鍵值對;其中 result 又是一層大括號,包著我們真正要的那幾個欄位。這裡推薦一個小工具 HiJson(網路上搜尋就有),把 JSON 貼進去就能看出一目瞭然的樹狀結構:

解析方式就是一層層剝開:

/** 解析 JSON */
private void Volley_Json(String json) {
    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONObject object = jsonObject.getJSONObject("result");
        tv_content.setText("歸屬地:" + object.getString("province") + "-"
                + object.getString("city") + "\n"
                + "區號:" + object.getString("areacode") + "\n"
                + "運營商:" + object.getString("company") + "\n"
                + "用戶類型:" + object.getString("card"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

new 一個 JSONObject 把字串丟進去,getJSONObject 取出子物件,再用 getString(name) 取值,就這麼簡單。

二、含陣列結構:JSONArray(笑話大全)

接口:

https://japi.juhe.cn/joke/content/list.from?key=你的key&page=1&pagesize=1&sort=asc&time=1418745237

一樣用 Volley 抓下來,得到的 JSON 是:

{
    "error_code": 0,
    "reason": "Success",
    "result": {
        "data": [
            {
                "content": "大腦:別睡了快起來吧要遲到了。 身體:滾,別煩我我還要再躺會。 時間:你倆慢慢吵我先溜了。 尿:再不起我就出來了!",
                "hashId": "0ee18f8733dc6744e6db6d0312839e5b",
                "unixtime": 1462885431,
                "updatetime": "2016-05-10 21:03:51"
            }
        ]
    }
}

我們要的是 content 那段文字。跟上一題的差別在於:這裡多了一個陣列,所以得改用 JSONArray 處理,解析前要先走訪:

/** 解析 JSON */
private void Volley_Json(String json) {
    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONObject jsonObject2 = jsonObject.getJSONObject("result");
        JSONArray ja = jsonObject2.getJSONArray("data");
        for (int i = 0; i < ja.length(); i++) {
            JSONObject jsonObject3 = (JSONObject) ja.get(i);
            tv_content.setText(jsonObject3.getString("content"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

思路是一層層往下:先取最外層的 result(JSONObject),再取 data(JSONArray),走訪後把每一筆強制轉型成 JSONObject,最後 getString("content") 拿資料。順序理清楚之後就不容易亂。

三、多層巢狀:JSONArray × 2(天氣預報)

這題也是專案裡實際用到的:JSON 裡有陣列,陣列裡還有陣列。聽起來複雜,但只要思路清楚,剩下就只是工作量的問題。

這裡使用和風天氣的接口,官網:https://www.heweather.com/

https://api.heweather.com/x3/weather?city=深圳&key=你的key
/** 取得天氣 */
private void getWeather(String city) {
    String url = "https://api.heweather.com/x3/weather?city=" + city + "&key=你的key";
    RequestQueue queue = Volley.newRequestQueue(this);
    StringRequest request = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                Log.i("json", json);
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError errorLog) {
                Log.e("Error", errorLog.toString());
            }
        });
    queue.add(request);
}

回傳的 JSON 相當長,這裡節錄關鍵結構:

{
    "HeWeather data service 3.0": [
        {
            "aqi": { "city": { "aqi": "60", "qlty": "良", "pm25": "42" } },
            "basic": {
                "city": "深圳",
                "cnty": "中國",
                "id": "CN101280601",
                "lat": "22.544000",
                "lon": "114.109000",
                "update": { "loc": "2016-05-10 22:07", "utc": "2016-05-10 14:07" }
            },
            "daily_forecast": [
                {
                    "astro": { "sr": "05:45", "ss": "18:54" },
                    "cond": { "code_d": "301", "code_n": "101", "txt_d": "強陣雨", "txt_n": "多雲" },
                    "date": "2016-05-10",
                    "hum": "70",
                    "tmp": { "max": "32", "min": "23" },
                    "wind": { "deg": "216", "dir": "無持續風向", "sc": "微風", "spd": "4" }
                }
                // 後續還有 2016-05-11 ~ 2016-05-16 等資料
            ],
            "hourly_forecast": [
                { "date": "2016-05-10 22:00", "hum": "89", "tmp": "27",
                  "wind": { "dir": "東風", "sc": "微風", "spd": "4" } }
            ],
            "now": {
                "cond": { "code": "101", "txt": "多雲" },
                "fl": "28", "hum": "88", "tmp": "25", "vis": "10",
                "wind": { "dir": "南風", "sc": "3-4", "spd": "14" }
            },
            "status": "ok",
            "suggestion": {
                "comf": { "brf": "較不舒適", "txt": "白天天氣多雲,同時會感到有些熱,不很舒適。" },
                "drsg": { "brf": "熱", "txt": "天氣熱,建議著短裙、短褲、短薄外套、T恤等夏季服裝。" },
                "uv":   { "brf": "弱", "txt": "紫外線強度較弱,建議出門前塗擦SPF在12-15之間、PA+的防曬護膚品。" }
            }
        }
    ]
}

對照結構圖來看就很清楚了:

最外層是陣列,陣列裡包著未來七天的天氣。這裡只取三天做示範:

/** 解析 JSON */
private void Volley_Json(String json) {
    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONArray jArray = jsonObject.getJSONArray("HeWeather data service 3.0");

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject jb1 = (JSONObject) jArray.get(i);
            JSONArray jr1 = jb1.getJSONArray("daily_forecast");

            for (int j = 0; j < jr1.length(); j++) {
                JSONObject jb2 = (JSONObject) jr1.get(j);
                JSONObject jb3 = jb2.getJSONObject("tmp");
                dateList.add(jb2.getString("date"));
                weatherList.add(jb2.getJSONObject("cond").getString("txt_n"));
                TmpList.add(jb3.getString("min") + "-" + jb3.getString("max"));
            }
        }

        // 填入畫面
        today_date.setText(dateList.get(0));
        today_weather.setText(weatherList.get(0));
        today_tmp.setText(TmpList.get(0));
        tomorrow_date.setText(dateList.get(1));
        tomorrow_weather.setText(weatherList.get(1));
        tomorrow_tmp.setText(TmpList.get(1));
        after_date.setText(dateList.get(2));
        after_weather.setText(weatherList.get(2));
        after_tmp.setText(TmpList.get(2));

        // 依天氣換圖
        setWeatherIcon(today_img, weatherList.get(0));
        setWeatherIcon(tomorrow_img, weatherList.get(1));
        setWeatherIcon(arter_img, weatherList.get(2));

    } catch (JSONException e) {
        e.printStackTrace();
    }
    // 清空資料,因為每次請求都只取前三天
    dateList.clear();
    weatherList.clear();
    TmpList.clear();
}

private void setWeatherIcon(ImageView iv, String weather) {
    if ("晴".equals(weather)) {
        iv.setImageResource(R.mipmap.sun);
    } else if ("多雲".equals(weather)) {
        iv.setImageResource(R.mipmap.cloudy);
    } else {
        iv.setImageResource(R.mipmap.rain);
    }
}

程式碼看起來長,但後半段其實只是填資料和換圖,可以略過不看。真正的重點在前半段:getJSONArray 取得整個陣列後開始走訪,強制轉型成 JSONObject,再取出每天的 daily_forecast 子陣列,重複同樣的程序,最後 getString(name) 取值。因為要拿三天資料,先分別裝進 List,取出來設到 TextView 上,最後記得清空 List。

三個例子由淺入深:JSONObject 處理單層鍵值對,JSONArray 處理列表,多層巢狀則是兩者反覆組合。掌握「先判斷這一層是物件還是陣列」這個原則,再深的結構也不難拆。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved