Android中關於Volley的使用(二)載入Json資料

來源:互聯網
上載者:User

前面一篇關於Volley的文章中,我們學習了如何利用ImageRequest去網路中載入圖片,那麼今天我們就來學習一下如何利用volley去網路中載入Json格式資料,並將其展示在一個ListView上。

1)資料來源:

private static final String WEATHER_LINK = "http://www.weather.com.cn/data/sk/101280101.html";

這是由中國天氣網提供的關於某個城市的天氣預告的Json資料,大家直接點選連結進去 http://www.weather.com.cn/data/sk/101280101.html 可以看到如下的資料:

{"weatherinfo":{"city":"廣州","cityid":"101280101","temp":"12","WD":"東風","WS":"2級","SD":"95%","WSE":"2","time":"21:05","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}

可以很清楚地看到這是一個Json格式的資料,其實JsonObject就是一個Map對象,所以這條連結提供的資料其實就是一個Weatherinfo的Map對象,它的屬性值是Weatherinfo,然後其值是另外一個JsonObject對象,假設叫O,則這個O對象有很多屬性,比如city,cityid,temp等,後面跟著的則是其對應的值。

那麼我們如何在Android中利用Volley去擷取這個資料呢?

2)Volley的應用

在這裡,我們就用一個ListView簡單地來展示其資料就好,先定義一個ListView,如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ListView        android:id="@+id/lvWeather"        android:layout_width="match_parent"        android:layout_height="match_parent" >    </ListView></LinearLayout>

然後,我們要為這個ListView設定資料來源,當然,我們先要去擷取資料,那麼接下來就是Volley的操作了。

跟前面ImageRequest的一樣,我們首先也是要定義一個RequestQueue,如下:

private RequestQueue mQueue;

mQueue = Volley.newRequestQueue(this);
接下來,由於上面我們分析過,這個連結返回來的資料只是一個Object,並不是一個數組,所以在這裡,我們需要使用的是JsonObjectRequest,而如果其它的連結返回來的是數組的結構,比如下面這樣:

{"list":[{"id":"2775","cover":"http:\/\/app.itabcd.com\/\/public\/uploads\/news\/531d37fc5f460.jpg","title":"599 \u5143\uff0cNokia X \u4eac\u4e1c\u9884\u7ea6\u5f00\u542f",

在上面這種情況中,我們可以看到list是一個數組(其後面帶有"[ ]"),那麼我們就要使用JsonArrayRequest了。

接著看代碼:

public void getWeatherInfo(){JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(WEATHER_LINK, null, new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject arg0) {list.clear();Iterator<String> it = arg0.keys();while(it.hasNext()){String key = it.next();JSONObject obj = null;try { obj = arg0.getJSONObject(key);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (obj != null) {Iterator<String> objIt = obj.keys();while (objIt.hasNext()) {String objKey = objIt.next();String objValue;try {objValue = obj.getString(objKey);HashMap<String, String> map = new HashMap<String, String>();map.put("title", objKey);map.put("content", objValue);Log.v(TAG, "title = " + objKey + " | content = " + objValue);list.add(map);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}Log.v(TAG, "list.size = " + list.size());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {}});mQueue.add(jsonObjectRequest);

在上面的代碼中,我們利用的是JsonObjectRequest中的建構函式:

    /**     * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is     * <code>null</code>, <code>POST</code> otherwise.     *     * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener)     */    public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,            ErrorListener errorListener) {        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,                listener, errorListener);    }
當我們將jsonRequest設定為null的時候,Volley會預設使用Get方式來發送我們的請求。

同樣的,跟ImageRequest一樣,我們需要實現兩個回呼函數,即兩個Listener,一個是正常返回的資料,一個是錯誤返回的資料。

我們主要看的是Response.Listener裡面的邏輯,在上面的代碼中,可以看到,我們首先利用參數arg0的迭代器,獲得第一個對象,此時,這個對象的key就是weatherinfo了,而其對應的值,其實還是一個JsonObject,所以,我們為了取得這個值裡面的鍵值,我們需要再去遍曆這個值中值,然後將其放到Map對象中,再將其放到list中。

其實邏輯很簡單,是不?

然後我們利用SimpleAdapter來將資料展示出來,就好了,如下:

setContentView(R.layout.activity_json);lvWeather = (ListView)findViewById(R.id.lvWeather);mQueue = Volley.newRequestQueue(this);getWeatherInfo();//{"weatherinfo":{"city":"廣州","cityid":"101280101","temp":"12","WD":"東風","WS":"2級","SD":"95%",//"WSE":"2","time":"21:05","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB"}}SimpleAdapter simpleAdapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, new String[] {"title","content"}, new int[] {android.R.id.text1, android.R.id.text2});lvWeather.setAdapter(simpleAdapter);

下面是:


嗯,簡單地應用就是這樣了。原始碼下載

關於如何利用Volley載入圖片,大家可以參考:

Android中關於Volley的使用(一)載入圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.