I have REST web service that has different responses containing some user information like this
{"id": 1,"fullname": "NV","login": "bravenewuser","sex": "M","mail":"[email protected]","photo": "","status": "","birthDate": "1900-01-11T00:00:00Z","registrationDate": "1900-05-13T00:00:00Z","phoneNumber": "9010"}
and like this
[{"id":2,"userId":0,"timeStart":"2017-08-21T13:05:00Z","active":true,"title":"Woman","artist":"Wolfmother","length":"00:04:00"},{"id":1,"userId":0,"timeStart":"2017-08-20T13:05:34Z","active":true,"title":"Dont call","artist":"Royal blood","length":"00:03:20"}]
with list of user's listenings
Say I have two classes User and Listening (may be in addition I need ListOfListenings wrapper-class). May be in future i would like to retrieve some more information from service and get responses having some another structure.
The question is what is the best way to parse different responses in one place (method or class) of the code?
I use com.loopj.android.http.AsyncHttpClient for calling service. So can I try something like this:
Write one common response handler for different types of response:
public class CommonResponseHandler <T extends Entity> extends AsyncHttpResponseHandler { private T response; public T getResponse() { return this.response; //return pasing result } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { /*parsing response body into this.response*/ } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { ///... } }and then call service like this
public User getUser(String url, RequestParams someparams) { AsyncHttpClient client = new AsyncHttpClient(); CommonResponseHandler<User> handler = new CommonResponseHandler<>(); client.get(url, someparams, handler ); return handler.getResponse(); }
Can I simplify parsing different types of responses by this way. And if not, what is better (or even the best) way to solve this problem? Thank you.