Gson结合Volley类:
package com.example.cuboo.myapplication;
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;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
/**
* Created by cuboo on 2016/10/26.
*/
public class GsonRequest<T> extends Request<T> {
private Response.Listener<T> mListener;
private Gson mGson;
private Class<T> mClass;
public GsonRequest(int method, String url,Class<T> mClass, Response.Listener<T> listener,Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mClass = mClass;
}
public GsonRequest(String url,Class<T> mClass, Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(Method.GET, url, mClass, listener, errorListener);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
String jsonString;
try {
jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(T response) {
this.mListener.onResponse(response);
}
}
数据类:
<pre style="font-family: 宋体; font-size: 9.8pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">package com.example.cuboo.myapplication;
public class weather {
private weatherinfo weatherinfo;
public weatherinfo getWeatherinfo() {
return weatherinfo;
}
public void setWeatherinfo(weatherinfo weatherinfo) {
this.weatherinfo = weatherinfo;
}
}
package com.example.cuboo.myapplication;
/**
* Created by cuboo on 2016/10/26.
*/
public class weatherinfo {
private String city;
private String temp;
private String time;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
使用:
RequestQueue mqueue = Volley.newRequestQueue(this);
GsonRequest<weather> gsonRequest = new GsonRequest<weather>
("http://www.weather.com.cn/data/sk/101010100.html"
, weather.class, new Response.Listener<weather>() {
@Override
public void onResponse(weather s) {
weatherinfo weatherInfo = s.getWeatherinfo();
Log.d("TAG", "city is " + weatherInfo.getCity());
Log.d("TAG", "temp is " + weatherInfo.getTemp());
Log.d("TAG", "time is " + weatherInfo.getTime());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("TAG", volleyError.getMessage(), volleyError);
}
});
mqueue.add(gsonRequest);