Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android JSON原生解析的幾種思路,以號碼歸屬地,笑話大全,天氣預報為例演示

Android JSON原生解析的幾種思路,以號碼歸屬地,笑話大全,天氣預報為例演示

編輯:關於Android編程

 

今天項目中要實現一個天氣的預覽,加載的信息很多,字段也很多,所以理清了一下思路,准備獨立出來寫一個總結,這樣對大家還是很有幫助的,老司機要開車了

涉及到網絡,你就一定要先添加權限,准沒錯


一.歸屬地查詢(JSONObject)


我們這裡以手機歸屬地為例來講述

這裡的接口

http://apis.juhe.cn/mobile/get?phone=18679606764&key=22a6ba14995ce26dd0002216be51dabb

這裡說明一下,我們現在以及接下來的例子,都會用到Volley來解析接口得到Json,所以不會用Volley的話可以先去看一下上面的兩篇文章

https://github.com/adamrocker/volley

Volley你到哪都能下載到,就不詳細說了

既然我們接口有了,我們就開始解析吧


    /**
     * 解析接口
     */
    private void Volley_Get() {

        String url = "http://apis.juhe.cn/mobile/get?phone=" + myPhone
                + "&key=22a6ba14995ce26dd0002216be51dabb";

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Method.PUBLIC, url,
                new Response.Listener() {
                    // 成功
                    @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,也就是今天本文中的主角

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

我們可以看到,JSON是由一個大括號括起來的,裡面是鍵值對,每一個鍵對應一個值,當然,他裡面還有一個result的大括號包裹著一堆數據,這裡我推薦一個工具叫

HiJson(網上有下,自行搜索一下就可以了)

我們來看他的構造

這裡寫圖片描述

這裡看起來就十分的清晰了,我們一層層的剝下來,這裡要用到的就是我們Z喎?/kf/ware/vc/" target="_blank" class="keylink">vcmcuanNvbs/CtcRKU09OT2JqZWN0wOA8L3A+DQo8L2Jsb2NrcXVvdGU+DQo8cHJlIGNsYXNzPQ=="brush:java;"> /** * 解析Json * * @param 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) { // TODO Auto-generated catch block e.printStackTrace(); } }

這裡,我們可以看到,我們new一個JSONObject 並且把json穿進去解析,然後getJSONObject獲取一個json裡面的字段,再去用getString(name)去獲取鍵得到值,所以運行結果

這裡寫圖片描述

是不是沒什麼難度?那我們來稍微做一個難一點的,笑話大全

二.笑話大全(JSONArray)

我們同樣的,需要一個接口

http://japi.juhe.cn/joke/content/list.from?key=56e5f85c150ebd54461ae4fb7c6705ec&page=1&pagesize=1&sort=asc&time=1418745237

然後我們繼續用Volley來解析這個接口得到Json

 /**
     * 解析接口
     */
    private void Volley_Get() {

        String url = "http://japi.juhe.cn/joke/content/list.from?key=56e5f85c150ebd54461ae4fb7c6705ec&page=1&pagesize=1&sort=asc&time=1418745237";

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Method.PUBLIC, url,
                new Response.Listener() {
                    // 成功
                    @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就是

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

我們需要的是中間的文字,但是這個json和之前那個json就有點不一樣了,這個明顯裡面有一個數組,所以我們要用JSONArray數組來解析了,我們先來看一下結構

這裡寫圖片描述

這個結構明顯要復雜一些,就在Data裡面他裡面還有一個數組,所以我們解析起來就要先遍歷一下了

 /**
     * 解析Json
     *
     * @param 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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

我們可以看到,我們是一層一層的去解析的,首先是解析得到最外面的result,返回的是一個JSONObject ,然後繼續解析data,返回的是一個JSONArray,然後我們遍歷一下 JSONObject jsonObject3 = (JSONObject) ja.get(i);強轉成一個JSONObject ,解析到最後我們就可以直接getString(“content”)拿到數據了,是不是思路很清晰?我們看一下效果圖

這裡寫圖片描述

三.天氣預報(JSONArray * 2)

這個也是比較復雜的,也是我項目中有用到的,就是一個JSON裡面有數組,數組裡面也有數組,這樣嵌套,其實說難也不難,只要掌握了思路,剩下的,只不過就是工作量的問題了

這裡我們用到的接口是和風天氣的接口

官網:http://www.heweather.com/

接口

https://api.heweather.com/x3/weather?city=%E6%B7%B1%E5%9C%B3&key=你的key

我們先用Volley解析接口

 /**
     * 獲取天氣
     *
     * @param city 城市名
     */
    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() {
                    // 成功
                    @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",
                    "co": "1",
                    "no2": "53",
                    "o3": "46",
                    "pm10": "65",
                    "pm25": "42",
                    "qlty": "良",
                    "so2": "7"
                }
            },
            "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",
                    "pcpn": "25.4",
                    "pop": "98",
                    "pres": "1008",
                    "tmp": {
                        "max": "32",
                        "min": "23"
                    },
                    "vis": "7",
                    "wind": {
                        "deg": "216",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "4"
                    }
                },
                {
                    "astro": {
                        "sr": "05:44",
                        "ss": "18:54"
                    },
                    "cond": {
                        "code_d": "101",
                        "code_n": "300",
                        "txt_d": "多雲",
                        "txt_n": "陣雨"
                    },
                    "date": "2016-05-11",
                    "hum": "64",
                    "pcpn": "0.0",
                    "pop": "13",
                    "pres": "1008",
                    "tmp": {
                        "max": "29",
                        "min": "23"
                    },
                    "vis": "10",
                    "wind": {
                        "deg": "118",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "10"
                    }
                },
                {
                    "astro": {
                        "sr": "05:44",
                        "ss": "18:55"
                    },
                    "cond": {
                        "code_d": "300",
                        "code_n": "101",
                        "txt_d": "陣雨",
                        "txt_n": "多雲"
                    },
                    "date": "2016-05-12",
                    "hum": "68",
                    "pcpn": "0.1",
                    "pop": "7",
                    "pres": "1009",
                    "tmp": {
                        "max": "29",
                        "min": "25"
                    },
                    "vis": "10",
                    "wind": {
                        "deg": "129",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "7"
                    }
                },
                {
                    "astro": {
                        "sr": "05:44",
                        "ss": "18:55"
                    },
                    "cond": {
                        "code_d": "101",
                        "code_n": "302",
                        "txt_d": "多雲",
                        "txt_n": "雷陣雨"
                    },
                    "date": "2016-05-13",
                    "hum": "69",
                    "pcpn": "9.8",
                    "pop": "53",
                    "pres": "1011",
                    "tmp": {
                        "max": "29",
                        "min": "23"
                    },
                    "vis": "7",
                    "wind": {
                        "deg": "123",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "1"
                    }
                },
                {
                    "astro": {
                        "sr": "05:43",
                        "ss": "18:56"
                    },
                    "cond": {
                        "code_d": "302",
                        "code_n": "302",
                        "txt_d": "雷陣雨",
                        "txt_n": "雷陣雨"
                    },
                    "date": "2016-05-14",
                    "hum": "73",
                    "pcpn": "5.3",
                    "pop": "66",
                    "pres": "1011",
                    "tmp": {
                        "max": "29",
                        "min": "23"
                    },
                    "vis": "10",
                    "wind": {
                        "deg": "115",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "10"
                    }
                },
                {
                    "astro": {
                        "sr": "05:43",
                        "ss": "18:56"
                    },
                    "cond": {
                        "code_d": "302",
                        "code_n": "302",
                        "txt_d": "雷陣雨",
                        "txt_n": "雷陣雨"
                    },
                    "date": "2016-05-15",
                    "hum": "69",
                    "pcpn": "7.7",
                    "pop": "58",
                    "pres": "1009",
                    "tmp": {
                        "max": "29",
                        "min": "22"
                    },
                    "vis": "10",
                    "wind": {
                        "deg": "166",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "4"
                    }
                },
                {
                    "astro": {
                        "sr": "05:42",
                        "ss": "18:57"
                    },
                    "cond": {
                        "code_d": "302",
                        "code_n": "101",
                        "txt_d": "雷陣雨",
                        "txt_n": "多雲"
                    },
                    "date": "2016-05-16",
                    "hum": "67",
                    "pcpn": "1.8",
                    "pop": "50",
                    "pres": "1008",
                    "tmp": {
                        "max": "28",
                        "min": "23"
                    },
                    "vis": "10",
                    "wind": {
                        "deg": "10",
                        "dir": "無持續風向",
                        "sc": "微風",
                        "spd": "8"
                    }
                }
            ],
            "hourly_forecast": [
                {
                    "date": "2016-05-10 22:00",
                    "hum": "89",
                    "pop": "38",
                    "pres": "1009",
                    "tmp": "27",
                    "wind": {
                        "deg": "80",
                        "dir": "東風",
                        "sc": "微風",
                        "spd": "4"
                    }
                }
            ],
            "now": {
                "cond": {
                    "code": "101",
                    "txt": "多雲"
                },
                "fl": "28",
                "hum": "88",
                "pcpn": "0",
                "pres": "1008",
                "tmp": "25",
                "vis": "10",
                "wind": {
                    "deg": "10",
                    "dir": "南風",
                    "sc": "3-4",
                    "spd": "14"
                }
            },
            "status": "ok",
            "suggestion": {
                "comf": {
                    "brf": "較不舒適",
                    "txt": "白天天氣多雲,同時會感到有些熱,不很舒適。"
                },
                "cw": {
                    "brf": "不宜",
                    "txt": "不宜洗車,路面積水較多,不宜擦洗汽車。如果執意擦洗,要做好濺上泥水的心理准備。"
                },
                "drsg": {
                    "brf": "熱",
                    "txt": "天氣熱,建議著短裙、短褲、短薄外套、T恤等夏季服裝。"
                },
                "flu": {
                    "brf": "少發",
                    "txt": "各項氣象條件適宜,無明顯降溫過程,發生感冒機率較低。"
                },
                "sport": {
                    "brf": "較適宜",
                    "txt": "天氣較好,戶外運動請注意防曬,推薦您在室內進行低強度運動。"
                },
                "trav": {
                    "brf": "適宜",
                    "txt": "天氣較好,但絲毫不會影響您出行的心情。溫度適宜又有微風相伴,適宜旅游。"
                },
                "uv": {
                    "brf": "弱",
                    "txt": "紫外線強度較弱,建議出門前塗擦SPF在12-15之間、PA+的防曬護膚品。"
                }
            }
        }
    ]
}

這裡,我們可以根據結構圖來分析

這裡寫圖片描述

這裡我們可以看到,他本身就是一個數組,接著又是一個數組,數組裡面包含著接下來七天的天氣情況,這裡呢,我們就不做的特別詳細了,我們寫三天 ,怎麼寫呢?看著哈


    /**
     * 解析Json
     *
     * @param 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));

            //設置圖片
            if (weatherList.get(0).equals("晴")) {
                today_img.setImageResource(R.mipmap.sun);
            } else if (weatherList.get(0).equals("多雲")) {
                today_img.setImageResource(R.mipmap.cloudy);
            } else {
                today_img.setImageResource(R.mipmap.rain);
            }

            if (weatherList.get(1).equals("晴")) {
                tomorrow_img.setImageResource(R.mipmap.sun);
            } else if (weatherList.get(1).equals("多雲")) {
                tomorrow_img.setImageResource(R.mipmap.cloudy);
            } else {
                tomorrow_img.setImageResource(R.mipmap.rain);
            }

            if (weatherList.get(2).equals("晴")) {
                arter_img.setImageResource(R.mipmap.sun);
            } else if (weatherList.get(2).equals("多雲")) {
                arter_img.setImageResource(R.mipmap.cloudy);
            } else {
                arter_img.setImageResource(R.mipmap.rain);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //清空數據
        dateList.clear();
        weatherList.clear();
        TmpList.clear();
    }

這裡代碼雖然多,但是後半部分基本上可以不看,就是設置數據和圖片的,我們這裡同樣的getJSONArray獲取到整個數組,然後開始遍歷這個數組,強轉為JSONObject 之後我們再次的獲取每天的小數組daily_forecast,到這裡,就和上面一樣了,我們又強轉為JSONObject 就可以開始getString(name)了,但是我們這裡要獲取三天的數據,所以我用一個List裝起來,然後拿出來設置到TextView上,然後再根據天氣設置圖片,最後,清空一下List,因為他每次請求我們都是只獲取他的前三天數據,所以運行的結果就是這樣:

這裡寫圖片描述

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved