Reputation: 5084
I need to send an array of type User[]
in the body of a GET request using retrofit2. This is what the final payload must look like:
body: {
"data_id": 1,
"data_provider": "string_value",
"users": [
{
user_id: 1,
name: 'name'
},
{
user_id: 1,
name: 'name'
},
...
]
}
Current API implementation looks like this:
@GET("api/users/submit.json")
Call<UserData> submitData(@Query("data_id") int data_id, @Query("data_provider") String data_provider, @Query("users[]") User[] users);
Arraylist code:
//Converting the ArrayList<User> usersList to an array
User[] userArray = usersList.toArray(new User[0]);
//The userArray is passed to the retrofit API along with the other request values (data_id, data_provider)
Upon logging the retrofit request, data_id
and data_provider
are correctly sent except for the User array. The user array looks like this:
api/users/submit.json?data_id=1&data_provider=test&users[]=com.testapp.models.User@7d57487
How can I send an array of type User
in the GET request body?
Upvotes: 3
Views: 1303
Reputation: 3376
For this payload:-
body: {
"data_id": 1,
"data_provider": "string_value",
"users": [
{
user_id: 1,
name: 'name'
},
{
user_id: 1,
name: 'name'
},
...
]
}
Api structure should be like this:-
public class ReqBody{
int data_id;
String data_provider;
User[] users;
}
@POST("api/users/submit.json")
Call<UserData> submitData(@Body ReqBody reqBody);
If your requirement is something else please attach the proper details for API as at some point you want to send data_id and data_provider in Query param and in the structure you have defined them as part of the body. If they are part of the body then it should be work like this.
Upvotes: 1
Reputation: 1061
You can send User object in request body using @Body annotation
Roughly it would look like this:
Your User Model
class User {
}
Users class which stores the list of Users
class RequestBody {
int data_id;
String data_provider;
List<User> users;
}
@POST("api/users/submit.json")
Call<UserData> submitData(@Body RequestBody requestbody);
You can read more about it in details here:
https://futurestud.io/tutorials/retrofit-send-objects-in-request-body
Upvotes: 2