Reputation: 256
Newbie here. I'm working on a simple client-server Android app with my friend, trying my best to write the cleanest most beautiful code that I can, strictly following the SOLID principles and using Design Patterns to decouple my classes and components. I wrote this method, hoping that it'll be the only networking code I'll have to write:
private void VolleyJSONPostParserRequest(String url, JSONObject requestBody,
final Handler handler, final IParser replyParser) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Object parsedResponse = replyParser.parse(response.toString());
notifyObservers(handler, parsedResponse);
} catch (Exception e) {
Log.e(TAG,handler.getClassName() + " reply parsing error!");
notifyObservers(handler, null); }
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG,"Error receiving response for " + handler.getClassName());
notifyObservers(handler, null);
}
});
}
To my discontent, I found out that sometimes the server's reply will be a JSONObject, and sometimes it will be a JSONArray. I do not want to copy-paste the entire thing and replace "JsonObjectRequest" with "JsonArrayRequest". What's a good solution for this problem? Or is it one of those cases where I'd be better off just copying and pasting?
Upvotes: 1
Views: 111
Reputation: 24114
In my opinion, you should implement a custom request (for example, public class CustomRequest extends Request<NetworkResponse>
). Please read the following Google's training doc for more information:
then...
@Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// Check if it is JSONObject or JSONArray
Object json = new JSONTokener(jsonString).nextValue();
if (json instanceof JSONObject) {
//do something...
} else if (json instanceof JSONArray) {
//do something...
} else {
//do something...
}
...
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
Upvotes: 1