custom gson convertor in retrofit using GETrequest - java

this is my retrofit interface
#GET
void getName(#Query("name") String name, Callback callback);
http request for above format is
/getName?name=abcd
but in my case url format should go like this
/getName?name=["abcd"]
what i want to change in my interface or any gson convertor required to append [""] to string. please give with example

I don't know about any simple way to do it using Retrofit APIs, but I would just create a method to do it and I would call it on every String I would pass to the adapter
public static String enclose(String text) {
return "[\""+text+"\"]";
}
And call it this way
getName(enclose("abcd"), new Callback<String>() {
#Override
public void success(String s, Response response) {
}
#Override
public void failure(RetrofitError error) {
}
});

Related

How to get JSON data by POST method with Secret code in android studio

I need to get json data response based on SECRET CODE with POST method, would you please solve my issue, thanks in advance.
I have been facing with many problems with this POST method of Secret Code to get the JSON Response
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewHeroes);
getQuestions();
}
private void getQuestions() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
ApiInterface api = retrofit.create(ApiInterface.class);
RequestModel requestModel = new RequestModel();
requestModel.setSecretCode("341977082");
Call<List<ModelObjects>> call = api.getQuestions();
call.enqueue(new Callback<List<ModelObjects>>() {
#Override
public void onResponse(Call<List<ModelObjects>> call, Response<List<ModelObjects>> response) {
List<ModelObjects> questionsList = response.body();
String[] questions = new String[questionsList.size()];
for (int i = 0; i < questionsList.size(); i++) {
questions[i] = questionsList.get(i).getQues_No();
}
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, questions));
}
#Override
public void onFailure(Call<List<ModelObjects>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});}}
Here is the interface and where I am passing the URL that contains parent and extension
public interface ApiInterface {
String BASE_URL = "";
#POST("QuestionsList")
Call<List<ModelObjects>> getQuestions();}
Here is the response Model
public class ModelObjects {
#SerializedName("Ques_No")
private String Ques_No;
public ModelObjects(String ques_No) {
Ques_No = ques_No;
}
public String getQues_No() {
return Ques_No;
}
public void setQues_No(String ques_No) {
Ques_No = ques_No;
}}
Here is the Request Model
public class RequestModel {
private String SecretCode;
public RequestModel(String secretCode) {
SecretCode = secretCode;
}
public RequestModel() {
}
public String getSecretCode() {
return SecretCode;
}
public void setSecretCode(String secretCode) {
SecretCode = secretCode;
}}
Here you have defined RequestModel but you are not passing it to the api call. Post request should have body.
So specify #Body while defining the api call as below.
#POST("QuestionsList")
Call<List<ModelObjects>> getQuestions(#Body RequestModel model);
Then while calling the getQuestion() pass the model.
RequestModel requestModel = new RequestModel();
requestModel.setSecretCode("341977082");
Call<List<ModelObjects>> call = api.getQuestions(requestModel);
Update :
update your ModelObject as below.
public class ModelObjects {
#SerializedName("Ques_No")
String Ques_No;
#SerializedName("Question")
String Ques;
#SerializedName("Answer")
String answer;
//same for other params as well
}
What can i see it, you are creating object of RequestModel class, but you are not passing it anywhere. If you want to send the secretCode along with the post network call, then you'll have to pass this requestModel instance to the call.
public interface ApiInterface {
String BASE_URL = "";
#POST("QuestionsList")
Call<List<ModelObjects>> getQuestions(#Body RequestModel requestModel);
}
then you can call this method and can pass this requestModel Object by
Call<List<ModelObjects>> call = api.getQuestions(requestModel);
If you want to access the first object you can do it by
List<ModelObjects> questionsList = response.body();
ModelObject obj = questionList.get(0);
String question = obj.getQues_No();
This question is going to be the first question.

Convert retrofit callback value to return enveloped object

My question is about the possibility to use RxJava for Android to manipulate data from a Retrofit call.
I've just started to use these libraries, so if my questions are trivial, please be patient.
This is my scenario.
I have a json returned from the server that looks like this
{ <--- ObjectResponse
higher_level: {
data: [
{
...
some fields,
some inner object: {
....
},
other fields
}, <----- obj 1
....,
{
....
}<---- obj n
]<-- array of SingleObjects
}
} <--- whole ObjectResponse
I've already have retrofit get this response and parsed in a ObjectResponse. Parsing this object, I can obtain a List that I can pass as usual to my RecyclerView Adapter.
So retrofit returned the ObjectResponse which is the model for the entire server answer, and in the retrofit callback I manipulate ObjectResponse to extract my List to be then passed to my adapter.
Right now, I have something like this
Call<ObjectResponse> call = apiInterface.getMyWholeObject();
call.enqueue(new Callback<ObjectResponse>() {
#Override
public void onResponse(Call<ObjectResponse> call, Response<ObjectResponse> response) {
//various manipulation based on response.body() that in the ends
// lead to a List<SingleObject>
mView.sendToAdapter(listSingleObject)
}
#Override
public void onFailure(Call<ObjectResponse> call,
Throwable t) {
t.printStackTrace();
}
});
My question is:
Is there a way to obtain from retrofit an Observable that can ultimate lead me to emit the list of SingleObject (and manipulate it) without have to manipulate ObjectResponse as I would do in the retrofit callback? Or should I have to stick with the retrofit callback and only after obatin List I can manipulate with RxJava just before feed this list to my Adapter?
I'd like to obtain something like this
apiInterface
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<SingleObject>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<Post> posts) {
mView.sendToAdapter(listSingleObject)
}
});
Retrofit converter factories solve that issue very nicely.
Jake Wharton talks about "envelope" objects in his "Making Retrofit Work For You" talk and points out how that can be solved.
Having defined an envelope class - a class with some extra fields that you do not care about:
public class Envelope<T> {
Meta meta;
List<Notification> notifications;
T response;
}
In this POJO fields meta and List<Notification> are being returned from the backend, but in the context of android app they are not interesting to us. Assume, that the real value that you need from the response is field named response, which might be any object (because it's generic).
Particularly in your example the POJO structure would be like this:
public class OriginalResponse {
HigherLevel higher_level;
}
public class HigherLevel {
Data data;
}
public class Data {
List<ActualData> list;
}
You have to implement your custom Converter.Factory:
public class EnvelopingConverter extends Converter.Factory {
#Nullable
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
Type envelopedType = TypeToken.getParameterized(Envelope.class, type).getType();
Converter<ResponseBody, Envelope<?>> delegate = retrofit.nextResponseBodyConverter(this, envelopedType, annotations);
return body -> {
Envelope<?> envelope = delegate.convert(body);
// Here return the object that you actually are interested
// in your example it would be:
// originalResponse = delegate.convert(body);
// return originalResponse.higher_level.data.list;
return envelope.response;
};
}
}
Add this converter to your retrofit builder:
new Retrofit.Builder()
...
.addConverterFactory(new EnvelopingConverter())
...
Then in your retrofit api interface instead of returning Single<OriginalResponse> return Single<List<ActualData>> directly:
interface Service {
#GET(...)
Single<List<ActualData>> getFoo();
}
Typical implementation in Kotlin:
class EnvelopeConverterFactory : Converter.Factory() {
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
val envelopedType: Type = TypeToken.getParameterized(ParentObject::class.java, type).type
val delegate: Converter<ResponseBody, ParentObject> =
retrofit.nextResponseBodyConverter(this, envelopedType, annotations)
return Converter<ResponseBody, ChildObject> { body -> delegate.convert(body)?.childObject }
}
}
As far as I know, there's no way to do it. For best practice, you should create a Facade layer (maybe an ApiManager class) to manage all your APIs. In that case, you can use map/flatMap to map your ObjectResponse to SingleObject like:
public Observable<List<SingleObject>> getSingleObjects(){
return ServiceGenerator.getApiMethods().getObjectResponse.map(new Function<ObjectResponse, List<SingleObject>>() {
#Override
public List<SingleObject> apply(ObjectResponse response) throws Exception {
return reponse.getListSingleObjects();
}
})
}
After some days, I can post my own solution.
It is inspired by the idea suggested by azizbekian.
The center idea is on the Envelope class, which I've express using retrofit annotation to be sure it would adapt to different JSON response from server, parsing the
higher_level: {
data: [
mid_level: { .. },
...
]
}
structure that I've already explained in my original post
public class WrapperResponse<T> {
#SerializedName(value="higher_level", alternate={"mid_level", "other"})
#Expose
DataResponse<T> data;
public DataResponse<T> getData() {
return data;
}
public void setData(DataResponse<T> data) {
this.data = data;
}
}
The focus here is in the parameters of SerializedName, where I specify all the possible JSON objects name that appear in my server response.
Then I have
public class UnwrapConverterFactory extends Converter.Factory {
private GsonConverterFactory factory;
public UnwrapConverterFactory(GsonConverterFactory factory) {
this.factory = factory;
}
#Override
public Converter<ResponseBody, ?> responseBodyConverter(final Type type,
Annotation[] annotations, Retrofit retrofit) {
Type wrappedType = new ParameterizedType() {
#Override
public Type[] getActualTypeArguments() {
return new Type[] {type};
}
#Override
public Type getOwnerType() {
return null;
}
#Override
public Type getRawType() {
return WrapperResponse.class;
}
};
Converter<ResponseBody, ?> gsonConverter = factory
.responseBodyConverter(wrappedType, annotations, retrofit);
return new WrapperResponseBodyConverter(gsonConverter);
}
}
and
public class WrapperResponseBodyConverter<T>
implements Converter<ResponseBody, T> {
private Converter<ResponseBody, WrapperResponse<T>> converter;
public WrapperResponseBodyConverter(Converter<ResponseBody,
WrapperResponse<T>> converter) {
this.converter = converter;
}
#Override
public T convert(ResponseBody value) throws IOException {
WrapperResponse<T> response = converter.convert(value);
return response.getData().getData();
}
}
Used in my Retrofit Module (dagger2) to ensure that my Retrofit client unwrap any answer from server using the generic WrapperResponse and, in the end, I can write Retrofit method as
#GET("locations")
Observable<List<Location>> getLocation();
where List is exactly the result I wanted to obtain: a list of objects straight from Retrofit response, that I can further elaborate with RxJava.
Thanks all.

android/java - Parsing JSON responses of different structure

I have REST web service that has different responses containing some user information like this
{"id": 1,"fullname": "NV","login": "bravenewuser","sex": "M","mail":"aaa#gmail.com","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.
You need two response handlers.
public class ObjectResponseHandler <T extends Entity> extends AsyncHttpResponseHandler {
private T response;
public T getResponse() {
return this.response; //return pasing result
}
}
And,
public class ArrayResponseHandler <T extends Entity> extends AsyncHttpResponseHandler {
private List<T> responses;
public List<T> getResponses() {
return this.responses; //return pasing result
}
}
And, if your JSON is only going to be a JsonArray or JsonObject. You can check for it using
anyJsonString.startsWith("[") => true => use ArrayResponseHandler
anyJsonString.startsWith("{") => true => use ObjectResponseHandler
If you want to keep using getResponse() as an object, you should create something like
public class ListWrapper<T> {
List<T> list;
public ListWrapper (List<T> list) { this.list = list; }
public List<T> getList () { return list; }
}
And, use it in ArrayResponseHandler, like
public ListWrapper getResponse() {
return new ListWrapper<T>(responses);
}

Custom object binding for JSON requests using Volley

I'm studying Volley library and in particular I'm dealing with JSONObject requests. In several tutorials I can find examples like this:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// ...
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// ...
}
});
but now I'm wondering if there is a way to bind a custom class to request object or result object.
I mean: I'd like to map the key-value result to some strong-typed custom object in my app domain. Is this possible or should I implement this feature by myself?
I guess it would help you.
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Method.POST,url,your_json_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// On Success
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// On Failure
}
});
MyApplication.getInstance().addToRequestQueue(jsObjRequest, tag);
Pass your your_json_object instead of mine.
Done
You can use Gson library like this:
https://gist.github.com/ficusk/5474673
Supposing your goal is to GET a Name object, where Name is defined as
public class Name{
private String firstName;
private String middleName;
private String lastName;
//constructor, getter, setter
}
then you could use Gson to convert the JSONObject to Name
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Gson gson = new Gson();
Name name = gson.fromJson(response.toString(),Name.class);
//use Name.
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// ...
}
});
#Lissf's answer is a good way to avoid boilerplate.
However, I would recommend checking out Retrofit which can reduce this down to a single line:
#GET ("/name")
getName(Callback<Name> nameCallback);
You might want to check out RxAndroid as well.

Volley REST client using JSON

I want to interact with a RESTful webservice that responds only in JSON.
Any successful response from the server has this syntax:
{
"code": int code,
"data": object or list of objects
}
while on error response:
{
"code": int code,
"error": string,
"details": string
}
So I made two classes in my Android project like this (for GSON reflection):
public class ErrorEntity {
private String details;
private String error;
private int code;
public ErrorEntity() {
// Stub constructor
}
public String getDetails() {
return details;
}
public String getError() {
return error;
}
public int getCode() {
return code;
}
}
For a successful response I made a generic because I don't want to parse JSON data on overridden parseNetworkResponse:
public class SuccessfulEntity<T> {
private T data;
private int code;
public SuccessfulEntity() {
// Stub content
}
public T getData() {
return data;
}
public int getCode() {
return code;
}
}
Now, because my RESTful server requires some custom headers, I need to make a Request subclass, but I don't know from which class I need to inherit.
I saw this question: Send POST request with JSON data using Volley and though to do something like that.
Basically, I want to make a new class (VolleyRestClient) which has GET, POST, DELETE methods and API routings, and with this class make all requests I need to do.
Methods of this class need to make a new custom request and parse new objects response like SuccessfulEntity and ErrorEntity, and then parsing data in service/thread that make the VolleyRestClient call.
How can I do that?
After a long fight with generics and type erasure, I finally did it.
So I'm posting this for whoever has the same issue like me and needs a solution without freaking out.
My ErrorEntity and my SuccessfulEntity are still the same, but I created a new interface called RepositoryListener, like this:
public interface RepositoryListener {
public abstract void onErrorResponse(int code, String details);
public abstract void onSuccessfulResponse(int code, Object obj);
public abstract void onSuccessfulResponse2(int code, List<Object> obj);
}
Then I made a class, VolleyRestClient, like this:
public class VolleyRestClient extends RestClient {
private final DefaultRetryPolicy mRetryPolicy;
private final RequestQueue mQueue;
private final Gson gson = new Gson();
public VolleyRestClient(Context context) {
// Default retry policy
mRetryPolicy = new DefaultRetryPolicy(2000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
mQueue = Volley.newRequestQueue(context);
}
public RequestQueue getQueue() {
// Method to push requests for image download
return mQueue;
}
#Override
public void GET(boolean obj, boolean needAuth, String url, Type type,
RepositoryListener listener) {
// Choose which listener to construct
Response.Listener<myResponse> mListener = obj ?
// This uses objects
makeSuccessfulListener(listener, type) :
// This uses list of objects
makeSuccessfulListener2(listener, type);
myRequest mRequest =
new myRequest(Request.Method.GET, needAuth, url,
mListener, makeErrorListener(listener));
mRequest.setRetryPolicy(mRetryPolicy);
mQueue.add(mRequest);
}
#Override
public void POST(boolean needAuth, String url, String body, Type type, RepositoryListener listener) {
myRequest mRequest = new myRequest(Request.Method.POST, needAuth, url, body,
makeSuccessfulListener(listener, type), makeErrorListener(listener));
mRequest.setRetryPolicy(mRetryPolicy);
mQueue.add(mRequest);
}
#Override
public void DELETE(boolean needAuth, String url, Type type, RepositoryListener listener) {
myRequest mRequest =
new myRequest(Request.Method.DELETE, needAuth, url,
makeSuccessfulListener(listener, type), makeErrorListener(listener));
mRequest.setRetryPolicy(mRetryPolicy);
mQueue.add(mRequest);
}
private Response.Listener<myRequest> makeSuccessfulListener
(final RepositoryListener listener, final Type type) {
// TODO: test this method and implement lists
if (listener == null) {
return null;
} else {
return new Response.Listener<myRequest>() {
#Override
public void onResponse(myRequest response) {
SuccessfulEntity<Object> obj = gson.fromJson(response.getBody(), type);
listener.onSuccessfulResponse(response.getCode(), obj.getData());
}
};
}
}
private Response.Listener<myRequest> makeSuccessfulListener2
(final RepositoryListener listener, final Type type) {
// TODO: test lists
if (listener == null) {
return null;
} else {
return new Response.Listener<myRequest>() {
#Override
public void onResponse(myReqyest response) {
SuccessfulEntity<List<Object>> obj = gson.fromJson(response.getBody(), type);
listener.onSuccessfulResponse2(response.getCode(), obj.getData());
}
};
}
}
private Response.ErrorListener makeErrorListener(final RepositoryListener listener) {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
String jError = new String(error.networkResponse.data);
ErrorEntity mError = gson.fromJson(jError, ErrorEntity.class);
// Invoke listener closure
listener.onErrorResponse(error.networkResponse.statusCode, mError.getDetails());
} catch (Exception e) {
listener.onErrorResponse(404, e.getMessage());
}
}
};
}
}
This is very dependant by my needs, but I'll explain the general concept.
So I have a custom request, as explained in my question, and I want to parse it to the correct data type.
To be more specific, I could have a JSONArray data only on GET requests (paginated elements, etc...) so I need to find a way to distinguish between this two cases (of course, I know in which cases I'll get a List or an Object).
We cannot simply create POJO from Json within a generic class using its type (because Java Type Erasure), so we need object type upfront.
But what we can do is:
in our custom request, on parseNetworkResponse, do something like that:
#Override
protected Response<myResponse> parseNetworkResponse(NetworkResponse response) {
try {
// Using server charset
myResponse mResponse = new myResponse();
mResponse.setCode(response.statusCode);
mResponse.setBody(new String(response.data,
HttpHeaderParser.parseCharset(response.headers)));
// Return new response
return Response.success(mResponse, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
// Normally use 'utf-8'
return Response.error(new ParseError(e));
}
}
In other words, copy the raw string response body onto a new object myResponse;
Response body will be eventually parsed in VolleyRestClient with the appropriate type passed as a GET/DELETE/POST argument;
makeSuccessfulListener and makeSuccessfulListener2 construct a Response.Listener from a RepositoryListener, which has 3 methods to override: onSuccessfulResponse for objects data, onSuccessfulResponse2 for list of objects data, onErrorResponse for 4XX/5XX errors;
Our data object/list will be parsed to more generics type (List and Object) and then passed to our custom listener RepositoryListener.
A full example for this approach:
public void getNewLogin(String nickname, String password,
final TextView author, final TextView title, final TextView text) {
String json =
(new StringBuilder()
.append("{ \"nickname\": \"")
.append(nickname)
.append("\", \"password\": \"")
.append(password)
.append("\" }")).toString();
mRest.POST(false, "http://192.168.0.104:8000/api/session", json,
new TypeToken<SuccessfulEntity<Login>>(){}.getType(),
new RepositoryListener() {
#Override
public void onSuccessfulResponse2(int code, List<Object> obj) {
// Nothing happens here
}
#Override
public void onSuccessfulResponse(int code, Object obj) {
UserSession mInstance = UserSession.getInstance(null);
Login newLogin = (Login) obj;
title.setText(newLogin.getToken());
mInstance.setToken(newLogin.getToken());
Log.i("onSuccessfulResponse", mInstance.getToken());
Log.i("onSuccessfulResponse", mInstance.getmAuthorizationToken());
if (newLogin.getUser() != null) {
author.setText(newLogin.getUser().getNickname());
text.setText(newLogin.getUser().getUniversity());
}
}
#Override
public void onErrorResponse(int code, String error) {
Log.i("onErrorResponse", error);
}
});
mRest is a VolleyRestClient object, which performs a POST request to that address with Type constructed by Gson TypeToken (remember, our body is a SuccessfulEntity).
Since we'll have an Object data for sure, we'll just override onSuccessfulResponse, cast data object to the same type T of SuccessfulEntity used in TypeToken, and do our dirty work.
I don't know if I was clear, this approach works, if some of you needs some clarification, just ask :)

Categories

Resources