Here some useful code snippets.
GsonRequest for GET petitions:
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
/**
* Convert a JsonElement into a list of objects or an object with Google Gson.
*
* The JsonElement is the response object for a {@link com.android.volley.Request.Method} GET call.
*
* @author https://plus.google.com/+PabloCostaTirado/about
*/
public class GsonGetRequest<T> extends Request<T>
{
private final Gson gson;
private final Type type;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* @param url URL of the request to make
* @param type is the type of the object to be returned
* @param listener is the listener for the right answer
* @param errorListener is the listener for the wrong answer
*/
public GsonGetRequest
(String url, Type type, Gson gson,
Response.Listener<T> listener, Response.ErrorListener errorListener)
{
super(Method.GET, url, errorListener);
this.gson = gson;
this.type = type;
this.listener = listener;
}
@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<T>) Response.success
(
gson.fromJson(json, type),
HttpHeaderParser.parseCacheHeaders(response)
);
}
catch (UnsupportedEncodingException e)
{
return Response.error(new ParseError(e));
}
catch (JsonSyntaxException e)
{
return Response.error(new ParseError(e));
}
}
}
GsonRequest for POST petitions:
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
/**
* Convert a JsonElement into a list of objects or an object with Google Gson.
*
* The JsonElement is the response object for a {@link com.android.volley.Request.Method} POST call.
*
* @author https://plus.google.com/+PabloCostaTirado/about
*/
public class GsonPostRequest<T> extends JsonRequest<T>
{
private final Gson gson;
private final Type type;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* @param url URL of the request to make
* @param type is the type of the object to be returned
* @param listener is the listener for the right answer
* @param errorListener is the listener for the wrong answer
*/
public GsonPostRequest
(String url, String body, Type type, Gson gson,
Response.Listener<T> listener, Response.ErrorListener errorListener)
{
super(Method.POST, url, body, listener, errorListener);
this.gson = gson;
this.type = type;
this.listener = listener;
}
@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<T>) Response.success
(
gson.fromJson(json, type),
HttpHeaderParser.parseCacheHeaders(response)
);
}
catch (UnsupportedEncodingException e)
{
return Response.error(new ParseError(e));
}
catch (JsonSyntaxException e)
{
return Response.error(new ParseError(e));
}
}
}
This is how you use it for JSON objects:
/**
* Returns a dummy object
*
* @param listener is the listener for the correct answer
* @param errorListener is the listener for the error response
*
* @return @return {@link com.sottocorp.sotti.okhttpvolleygsonsample.api.GsonGetRequest}
*/
public static GsonGetRequest<DummyObject> getDummyObject
(
Response.Listener<DummyObject> listener,
Response.ErrorListener errorListener
)
{
final String url = "http://www.mocky.io/v2/55973508b0e9e4a71a02f05f";
final Gson gson = new GsonBuilder()
.registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
.create();
return new GsonGetRequest<>
(
url,
new TypeToken<DummyObject>() {}.getType(),
gson,
listener,
errorListener
);
}
This is how you use it for JSON arrays:
/**
* Returns a dummy object's array
*
* @param listener is the listener for the correct answer
* @param errorListener is the listener for the error response
*
* @return {@link com.sottocorp.sotti.okhttpvolleygsonsample.api.GsonGetRequest}
*/
public static GsonGetRequest<ArrayList<DummyObject>> getDummyObjectArray
(
Response.Listener<ArrayList<DummyObject>> listener,
Response.ErrorListener errorListener
)
{
final String url = "http://www.mocky.io/v2/5597d86a6344715505576725";
final Gson gson = new GsonBuilder()
.registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
.create();
return new GsonGetRequest<>
(
url,
new TypeToken<ArrayList<DummyObject>>() {}.getType(),
gson,
listener,
errorListener
);
}
This is how you use it for POST calls:
/**
* An example call (not used in this example app) to demonstrate how to do a Volley POST call
* and parse the response with Gson.
*
* @param listener is the listener for the success response
* @param errorListener is the listener for the error response
*
* @return {@link com.sottocorp.sotti.okhttpvolleygsonsample.api.GsonPostRequest}
*/
public static GsonPostRequest getDummyObjectArrayWithPost
(
Response.Listener<DummyObject> listener,
Response.ErrorListener errorListener
)
{
final String url = "http://PostApiEndpoint";
final Gson gson = new GsonBuilder()
.registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
.create();
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "Ficus");
jsonObject.addProperty("surname", "Kirkpatrick");
final JsonArray squareGuys = new JsonArray();
final JsonObject dev1 = new JsonObject();
final JsonObject dev2 = new JsonObject();
dev1.addProperty("name", "Jake Wharton");
dev2.addProperty("name", "Jesse Wilson");
squareGuys.add(dev1);
squareGuys.add(dev2);
jsonObject.add("squareGuys", squareGuys);
return new GsonPostRequest<>
(
url,
jsonObject.toString(),
new TypeToken<DummyObject>()
{
}.getType(),
gson,
listener,
errorListener
);
}
}
All the code is taken from here, and you have a blog post about how to use OkHttp, Volley and Gson here.
Volley
request. If I'm not mistaken, GSON should be able to convert an object directly to aJSON
object, just by callinggson.toJson(myObject)
. Also check out this tutorial: mkyong.com/java/… for parsing objects to and from Json. – Cnossus