jwBurnside jwBurnside - 5 months ago 19
Java Question

Creating a generic class and parameter in Java

I have a general sendRequest() method that I use to get a json result back from the server. I'm parsing the result in an instance of the callback right now, but instead I'd much rather just pass in a type to the sendRequest() method so I can parse and handle exceptions before the callback. How can I do this? I've included the relevant code and some comments below.

public void sendRequest(int method, String url, final RequestListener listener) {
StringRequest postRequest = new StringRequest(method, url,
new Response.Listener<String>()
public void onResponse(String response) {
listener.gotResponse(response, null);

// Instead of parsing this into a user object, I'd like to parse it into
// a type that I pass into the sendRequest() method.
try {
User user = User.parseJson(new JSONObject(response));
} catch (JSONException e) {


First of all please note that out of the box you have JsonObjectRequest which will convert the response directly into a JSONObject which seems to be better than StringRequest in your case, but as you want to go a little bit further I would propose to create a custom request based on a generic unmarshaller.

public interface JsonUnmarshaller<T> {
    T parse(JSONObject object) throws JSONException;

The custom request could be something like this:

public class JSONRequest extends Request<T> {
    private final Listener<T> mListener;
    private final JsonUnmarshaller<T> unmarshaller;

    public JSONRequest(int method, String url, Listener<T> listener,
        ErrorListener errorListener, JsonUnmarshaller<T> unmarshaller) {
        super(method, url, errorListener);
        mListener = listener;
        this.unmarshaller = unmarshaller;

    protected void deliverResponse(T response) {
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(
                response.data, HttpHeaderParser.parseCharset(response.headers)
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        try {
            return Response.success(
                unmarshaller.parse(new JSONObject(parsed)), 
        } catch (JSONException je) {
            return Response.error(new ParseError(je));

Then your method would be:

public <T> void sendRequest(int method, String url, final RequestListener 
                            listener, JsonUnmarshaller<T> unmarshaller) {
    JSONRequest postRequest = new JSONRequest(...