I'd recommend to stick to the GSON library for JSON parsing. Here's how a Volley request with embedded JSON processing could look then:
import java.io.UnsupportedEncodingException;
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.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* Volley GET request which parses JSON server response into Java object.
*/
public class GsonRequest<T> extends Request<T> {
/** JSON parsing engine */
protected final Gson gson;
/** class of type of response */
protected final Class<T> clazz;
/** result listener */
private final Listener<T> listener;
public GsonRequest(String url, Class<T> clazz, Listener<T> listener,
ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.listener = listener;
this.gson = new Gson();
}
@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, clazz), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
Let's imagine you have a server method located at http://example.com/api/persons/ which returns a JSON array of Person; Person is as follows:
public class Person {
String firstName;
String lastName;
}
We can call the abovementioned method like this:
GsonRequest<Person[]> getPersons =
new GsonRequest<Person[]>("http://example.com/api/persons/", Person[].class,
new Listener<Person[]>() {
@Override
public void onResponse(Person[] response) {
List<Person> persons = Arrays.asList(response);
// TODO deal with persons
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO deal with error
}
});
VolleyQueue.get().add(getPersons);
And finally in response listener we get an array of Person which can be converted to list and fed to ListView's adapter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…