Created
October 7, 2013 07:53
-
-
Save beshkenadze/6864024 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** Volley request parsing JSON strings using the gson deserializer */ | |
| public class GsonRequest<T> extends Request<T> { | |
| /** Type of Generic. */ | |
| private final Class<T> mTypeOfT; | |
| /** Response listener */ | |
| private final Response.Listener<T> mListener; | |
| /** GSON parser */ | |
| private final Gson mGson; | |
| /** | |
| * Create a new GSON JSON-parser request. | |
| * | |
| * @param typeOfT Type of generic. | |
| * @param url Request url. | |
| * @param listener Response listener. | |
| * @param errorListener Error listener. | |
| */ | |
| public GsonRequest(final Class<T> typeOfT, final String url, final Response.Listener<T> listener, | |
| final Response.ErrorListener errorListener) { | |
| this(typeOfT, url, listener, errorListener, new Gson()); | |
| } | |
| /** | |
| * Create a new GSON JSON-parser request with a custom gson instance (useful for specifying | |
| * custom date formats, etc.) | |
| * | |
| * @param typeOfT Type of generic. | |
| * @param url Request url. | |
| * @param listener Response listener. | |
| * @param errorListener Error listener. | |
| * @param gson Custom GSON instance. | |
| */ | |
| public GsonRequest(final Class<T> typeOfT, final String url, final Response.Listener<T> listener, | |
| final Response.ErrorListener errorListener, final Gson gson) { | |
| super(Method.GET, url, errorListener); | |
| mListener = listener; | |
| mTypeOfT = typeOfT; | |
| mGson = gson; | |
| } | |
| @Override | |
| protected Response<T> parseNetworkResponse(final NetworkResponse response) { | |
| try { | |
| final String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); | |
| return Response.success(mGson.fromJson(jsonString, mTypeOfT), | |
| HttpHeaderParser.parseCacheHeaders(response)); | |
| } catch (Exception e) { | |
| return Response.error(new ParseError(e)); | |
| } | |
| } | |
| @Override | |
| protected void deliverResponse(final T response) { | |
| if (!isCanceled() && (mListener != null)) { | |
| mListener.onResponse(response); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment