日期:2014-05-16  浏览次数:20365 次

Android中关于Volley的使用(二)加载Json数据

前面一篇关于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>() {
				@Override
				public 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 block
							e.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);