Retrofit parse array of strings - android

I have troubles with parsing of server response using retrofit. Server returns array of strings, how it's possible to parse this: ["1", "21", "22"] using retrofit framework. I'm using Retrofit 2.0.0-beta2.
Thanks

To parse that response define your method in API interface like this:
#GET("methodThatReturnsArray")
Call<ArrayList<String>> methodThatReturnsArray();
Synchronous call would look like
Call<ArrayList<String>> call = retrofitService.methodThatReturnsArray();
Response response = call.execute();
ArrayList<String> arrayOfStrings = response.body();

Related

Getting different Json Array element Order in Retrofit and Postman

I hit same API from Postman & Retrofit. Postman returns correct JSON array elements order but in Retrofit i get shuffled results.
I am expecting the same JSON array element order in retrofit as i get in postman.
POSTMAN parameters
{
"campusId":1,
"reported":true,
"size":30,
"status":[5,6,7,8],
"sortBy":"updatedAt",
"sortDirection":"desc",
"page":1
}
Retrofit Parameters
Map<String,Object> body = new HashMap<>();
body.put("campusId",1);
body.put("reported",true);
body.put("size",30);
body.put("status", Arrays.asList(5,6,7,8));
body.put("sortBy ","updatedAt");
body.put("sortDirection","desc"); //desc
body.put("page",1);

how can i post nested json objects to server in retrofit [duplicate]

This question already has answers here:
Retrofit2 Post body as Json
(2 answers)
Closed 4 years ago.
How can I post to the server? I need to post an JSON object using Retrofit 2. My JSON object is
{
"test_id":5,
"user_id":null,
"org_id":2,
"schedule_id":15,
"group_id":null,
"next_section_id":"",
"current_section":
{}
}
make give json into one pojo class and pass into api calling like..
#POST("path")
Call<ResponseData> passJsonData(#Body JsonData jsonData); // here pass your request data pojo class object..
when calling that time only create object and pass all data into object and pass into api call method.
like ..
JsonData data=new JsonData();
data.setId("1");
data.setName("Abcd");
Call<ResponseData> responseCall =apiInterface.passJsonData(data);
Below are some ways to achieve this:
1.
#POST("/path")
void sendPost(#Body EventPayload body, Callback<Response> onSuccess);
here EventPayload is the POJO representation of your request
2.
#POST("/path")
void sendPost(#Body String body, Callback<Response> onSuccess);
here body is the serialized JSON in the string form

How to parse dynamic JSON with Retrofit?

I have dynamic JSON, here is example: http://pastebin.com/QMWRZTrD
How I can parse it with Retrofit?
I failed to generate POJO classes, since I have dynamic fields like "5411" and "5412".
EDIT:
I solved it by using Map, since first value is always integer, and second is list of objects.
#FormUrlEncoded
#POST("history.php")
Observable<Map<Integer, List<Vehicle>>> getHistory(#Field("uredjaji") String vehicleId, #Field("startDate") String startDATE, #Field("endDate")
you can use Map to serialize and deserialize it in case of Random keys.
Observable<Map<Integer, List<YourObject>>>
You can get retrofit api call to return String in your RestApi Interface like
Call<String> method(#Path(..)...);
And for that to work you would need to add the scalars converter factory to where you create your Retrofit object.
First you would need to import it:
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
And then add it:
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://your.base.url/")
.build();
And then in onResponse
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
Type mapType = new TypeToken<Map<String,List<SomeClass>>() {}.getType(); // define generic type
Map<String,List<SomeClass>> result= gson.fromJson(response.body(), mapType);
} else {
}
}
Also,check out this site it has great tutorials on Retrofit.

Android Retrofit Post Issue

I previously implemented the following post request with volley but now i want to use it for retrofit.
So my rest webservice is the following
www.blahblahblah.com/webservice.svc/
I have a function (Person) that is called in the webservice that accepts the following jsonobject
JSONObject jsonObject = new JSONObject();
JSONObject searchCriteria = new JSONObject();
jsonObject.put("FullName", "frank jones");
jsonObject.put("DOB", "06-04-1978");
jsonObject.put("Age", "28");
jsonObject.put("Reason", "Search");
searchCriteria.put("searchCriteria", jsonObject);
So in volley i call www.blahblahblah.com/webservice.svc/Person
and pass the above jsonobject.
Works perfectly
So for Retrofit i've used the same logic, create my jsonobject and pass it in the request
So i use the same url www.blahblahblah.com/webservice.svc/
Create my Post
#POST("Person")
Call<PersonResponseData> getPersonAccess(#Body Object body);
so then my code to get the response
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(urlSearch)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitService service = retrofit.create(RetrofitService.class);
Call<PersonResponseData> personResponseDataCall = service.getPersonAccess(searchCriteria);
personResponseDataCall.enqueue(new Callback<PersonResponseData>() {
#Override
public void onResponse(Response<PersonResponseData> response, Retrofit retrofit) {
int statuscode = response.code();
PersonResponseData personResponseData = response.body();
}
#Override
public void onFailure(Throwable t) {
}
});
I just get a 404 error, any ideas.
As i said this works perfectly in volley but I've done something wrong in retrofit.
Thanks for your help
You can review this question link here is a explanation for use retrofit 2 with POST request
That's only guess, but try following:
1) in Call declaration specify it, not Call getPersonAccess, but Call<PersonResponseData> getPersonAccess;
2) make POJO instead of JSON object and use it as a body instead of passing Object into getPersonAccess call.

Directly POST JSONObject via retrofit

Can I send JSON directly via retrofit like this:
#POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(#NonNull #Body JSONObject jsonObject);
You can use TypedInput
#POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(#NonNull #Body TypedInput body);
And to form param:
TypedInput in = new TypedByteArray("application/json", jsonObject.toString().getBytes("UTF-8"));
And use in as a parameter for request.
You can directly post JSON objects using GSONs JsonObject class.
The reason Googles JSONObject does not work is that retrofit uses GSON by default and tries to serialize the JSONObject parameter as a POJO. So you get something like:
{
"JSONObject":
{
<your JSON object here>
}
}
If what you are doing requires you to use JSONObject then you can simply convert between the two using the String format of the object.

Categories

Resources