/**
* 自定义JsonRequest
* Created by lezg on 2014/8/16.
*/
public class MyJsonRequest extends JsonRequest<ArrayList<News>> {
public MyJsonRequest(String url,Response.Listener<ArrayList<News>> listener,
Response.ErrorListener errorListener) {
this(Method.GET, url,listener, errorListener);
}
public MyJsonRequest(int method, String url,
Response.Listener<ArrayList<News>> listener,
Response.ErrorListener errorListener) {
super(method, url, null, listener, errorListener);
}
@Override
protected Response<ArrayList<News>> parseNetworkResponse(NetworkResponse response) {
try {
String name = Thread.currentThread().getName();
System.out.println(name);
ArrayList<News> result = new ArrayList<News>();
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
JSONObject jsonObject = new JSONObject(json).getJSONObject("value");
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject item = jsonArray.getJSONObject(i);
News newData = new News();
newData.setTitle(item.optString("title"));
newData.setDescription(item.optString("description"));
newData.setPublishDate(item.optString("pubDate"));
result.add(newData);
}
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}catch (JSONException e){
return Response.error(new ParseError(e));
}
}
}
public class GsonRequest<T> extends Request<T> {
private final Class<T> mClazz;
private final Response.Listener<T> mListener;
public GsonRequest(String url, Class<T> mClazz, Response.Listener<T> listener,
Response.ErrorListener errorListener) {
this(Method.GET, url, mClazz, listener, errorListener);
}
public GsonRequest(int method, String url, Class<T> mClazz, Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mClazz = mClazz;
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Gson gson = new Gson();
return Response.success(gson.fromJson(jsonStr, mClazz), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}