Skip to content

Instantly share code, notes, and snippets.

@ryanbateman
Last active December 17, 2015 14:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanbateman/5625768 to your computer and use it in GitHub Desktop.
Save ryanbateman/5625768 to your computer and use it in GitHub Desktop.
An attempt at a GsonObjectRequest that will post and return objects using Volley
package com.example.network.requests;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.example.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public abstract class GsonObjectRequest<R, T> extends Request<T> {
protected Gson gson;
private Listener<T> listener;
private Class<R> inputType;
private Class<T> outputType;
private R object;
private static final String PROTOCOL_CHARSET = "utf-8";
public GsonObjectRequest(int method, String url, R postObject, Class<R> inputType, Class<T> outputType, Listener<T> listener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.inputType = inputType;
this.outputType = outputType;
this.object = postObject;
gson = Utils.getGson();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = null;
return headers != null ? headers : super.getHeaders();
}
@Override
public byte[] getBody() {
String jsonString = gson.toJson(object, inputType);
try {
return jsonString.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException e) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", jsonString, PROTOCOL_CHARSET);
return null;
}
}
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(gson.fromJson(json, outputType), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment