public class XmlRequest extends Request<XmlPullParser> { private Listener<XmlPullParser> listener; public XmlRequest(int method, String url, Listener<XmlPullParser> listener, ErrorListener errorlistener) { super(method, url, errorlistener); this.listener = listener; } public XmlRequest(String url, Listener<XmlPullParser> listener, ErrorListener errorlistener) { this(Method.GET, url, listener, errorlistener); } @Override protected Response<XmlPullParser> parseNetworkResponse( NetworkResponse response) { try { String str = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new StringReader(str)); return Response.success(parser, HttpHeaderParser.parseCacheHeaders(response)); } catch (Exception e) { return Response.error(new ParseError()); } } @Override protected void deliverResponse(XmlPullParser response) { listener.onResponse(response); } }
十、自定义Request2(GsonRequest)
对于上面的JsonObjectRequest,我们只是得到了JSONObject,��想Gson,我们是否也可以直接把获取到的Json数据转换为一个实体对象呢?当然可以,而且也非常简单;
public class GsonRequest<T> extends Request<T> { private Listener<T> listener; private Gson gson; private Class<T> clazz; public GsonRequest(int method, String url, Class<T> clazz, Listener<T> listener, ErrorListener errorlistener) { super(method, url, errorlistener); this.listener = listener; this.clazz = clazz; gson = new Gson(); } public GsonRequest(String url, Class<T> clazz, Listener<T> listener, ErrorListener errorlistener) { this(Method.GET, url, clazz, listener, errorlistener); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String str = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(gson.fromJson(str, clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(T response) { listener.onResponse(response); } }