1. 程式人生 > >Gson解析和Volley框架並用

Gson解析和Volley框架並用

package com.example.liuyazhou.mythirdapplication;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

import weather.Data;
import weather.Life;
import weather.Info;
import weather.Realtime;
import weather.Result;
import weather.ALLWeather;

public class MainActivity extends Activity {

    private Button button;

    private String urlJsonWeather = "http://op.juhe.cn/onebox/weather/query?cityname=%E5%8C%97%E4%BA%AC&dtype=json&key=******1b7942cbdcff19a08001";
    private static String TAG = MainActivity.class.getSimpleName();/////key需要自己申請
    private String jsonResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                funWeatherGsonRequest();
            }
        });
    }
    ////Volley 三  http://blog.csdn.net/guolin_blog/article/details/17612763
    public void funWeatherGsonRequest() {
        RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
        GsonRequest<ALLWeather> gsonRequest = new GsonRequest<ALLWeather>(
                urlJsonWeather, ALLWeather.class,
                new Response.Listener<ALLWeather>() {
                    @Override
                    public void onResponse(ALLWeather allWeather) {
                        Log.i(TAG, allWeather.toString());
                        Log.i(TAG, "reason is: " + allWeather.getReason());

                        Result result = allWeather.getResult();
                        Log.i(TAG, "result is: "+result.toString());
                       Data data = result.getData();
                        Log.i(TAG, "data is: "+data.toString());

                        Realtime realtime =data.getRealtime();
                        Log.i(TAG, "realtime is: "+realtime.toString());
                        Log.i(TAG, "realtime.getCity_code(): "+ realtime.getCity_code());

                        Life life  = data.getLife();
                        Log.i(TAG, "life is: "+life.toString());
                        Log.i(TAG, " life.getDate(): "+ life.getDate());


                        Info lifeInfo  = life.getInfo();///這裡物件名是lifeInfo是允許的
                        Log.i(TAG, "lifeInfo is: "+lifeInfo.toString());
//                        Log.i(TAG, "chuanyi is: "+lifeInfo.toString());
                       Log.i(TAG, "chuanyi is: " + lifeInfo.getChuanyi()[0]+","+lifeInfo.getChuanyi()[1]);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }
        });
        mQueue.add(gsonRequest);
    }
}
package weather;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class ALLWeather {
    private String reason;
    private Result result;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }
}
package weather;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class Result {
    private Data data;

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }
}
package weather;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class Data {
    private Realtime  realtime;
    private  Life life;

    public Realtime getRealtime() {
        return realtime;
    }

    public void setRealtime(Realtime realtime) {
        this.realtime = realtime;
    }

    public Life getLife() {
        return life;
    }

    public void setLife(Life life) {
        this.life = life;
    }
}
package weather;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class Realtime {
//    "city_code":"101010100",
//            "city_name":"北京",
//            "date":"2016-09-15",
//            "time":"15:00:00",
//            "week":4,
//            "moon":"八月十五",
//            "dataUptime":1473925023,
  //  private  String  cityCode;
private  String  city_code;


//    public String getCityCode() {  ////返回null
//        return cityCode;
//    }
//
//    public void setCityCode(String cityCode) {
//        this.cityCode = cityCode;
//    }

    public String getCity_code() {
        return city_code;
    }

    public void setCity_code(String city_code) {
        this.city_code = city_code;
    }

}
package weather;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class Life {
   private  String  date;
   // private Info lifeInfo;////錯誤的,類定義中的屬性名、物件名、類名要與json裡的key一致
   private Info info;
    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public Info getInfo() {
        return info;
    }

    public void setInfo(Info info) {
        this.info = info;
    }
}
package weather;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class Info {

//    "info":{
//        "chuanyi":[
//        "熱",
//                "天氣熱,建議著短裙、短褲、短薄外套、T恤等夏季服裝。"
//        ],
//        "ganmao":[
//        "少發",
//                "各項氣象條件適宜,發生感冒機率較低。但請避免長期處於空調房間中,以防感冒。"
//        ],

    private  String[] chuanyi;
    private  String[] ganmao;

    public String[] getChuanyi() {
        return chuanyi;
    }

    public void setChuanyi(String[] chuanyi) {
        this.chuanyi = chuanyi;
    }

    public String[] getGanmao() {
        return ganmao;
    }

    public void setGanmao(String[] ganmao) {
        this.ganmao = ganmao;
    }
}


package com.example.liuyazhou.mythirdapplication;

/**
 * Created by liuyazhou on 2016/9/15.
 */
////Volley 三  http://blog.csdn.net/guolin_blog/article/details/17612763
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;

/**
 * Created by liuyazhou on 2016/9/15.
 */
public class GsonRequest<T> extends Request<T> {

    private final Response.Listener<T> mListener;

    private Gson mGson;

    private Class<T> mClass;

    public GsonRequest(int method, String url, Class<T> clazz, Response.Listener<T> listener,
                       Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        mGson = new Gson();
        mClass = clazz;
        mListener = listener;
    }

    public GsonRequest(String url, Class<T> clazz, Response.Listener<T> listener,
                       Response.ErrorListener errorListener) {
        this(Method.GET, url, clazz, listener, errorListener);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(mGson.fromJson(jsonString, mClass),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }

}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.liuyazhou.mythirdapplication.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="點選"
        android:id="@+id/button"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="74dp" />

</RelativeLayout>


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.liuyazhou.mythirdapplication">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

{//AllWeather //////返回的JSON資料
	"reason":"successed!",
	"result":{ //Result
		"data":{ //Data
			"realtime":{ //Realtime
				"city_code":"101010100",
				"city_name":"北京",
				"date":"2016-09-15",
				"time":"15:00:00",
				"week":4,
				"moon":"八月十五",
				"dataUptime":1473925023,
				"weather":{//Weather
					"temperature":"30",
					"humidity":"47",
					"info":"多雲",
					"img":"1"
				},
				"wind":{ //Wind
					"direct":"西南風",
					"power":"2級",
					"offset":null,
					"windspeed":null
				}
			},
			"life":{ //Life
				"date":"2016-9-15",
				"info":{  //Info
					"chuanyi":[
						"熱",
						"天氣熱,建議著短裙、短褲、短薄外套、T恤等夏季服裝。"
					],
					"ganmao":[
						"少發",
						"各項氣象條件適宜,發生感冒機率較低。但請避免長期處於空調房間中,以防感冒。"
					],
					......................
jar檔案需要自己下載