Reputation: 21
here are the nested JSON request
{
"user": {
"email": "[email protected]",
"password": "12345678"
}
}
here are the nested JSON response
{
"data": {
"renew_token": "e994c4d2-d93b-47e8-ab5f-9090b823f249",
"token": "419fff70-b1ee-4ea7-b636-ddbec6346794"
}
}
i am able to post the request but i'm struggling to code the response in the same process
my interface currently
public interface JsonApi {
@POST("session")
Call<RootUser> userLogin(@Body RootUser rootUser);
}
Model for request
public class User{
public String email;
public String password;
}
public class RootUser{
public User user;
}
the API call
private void userLogin(){
String email = etloginemail.getText().toString();
String password = etloginpassword.getText().toString();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://the-digest-app.herokuapp.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonApi jsonApi = retrofit.create(JsonApi.class);
User user = new User(email, password);
RootUser rootUser = new RootUser(user);
Call<RootUser> call = jsonApi.userLogin(rootUser);
call.enqueue(new Callback<RootUser>() {
@Override
public void onResponse(Call<RootUser> call, Response<RootUser> response) {
Toast.makeText(LoginActivity.this, "Success", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<RootUser> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
How to define the get response function? if i did something wrong, kindly tell me!
Upvotes: 0
Views: 117
Reputation: 411
You should create one more POJO for response like
public class LoginResponse{
@SerializedName("renew_token")
public String renewToken;
@SerializedName("token")
public String token;
}
public class UserLoginResponse{
public LoginResponse data;
}
and your retrofit interface should look like
public interface JsonApi {
@POST("session")
Call<UserLoginResponse> userLogin(@Body RootUser rootUser);
}
and your call implementation
call.enqueue(new Callback<UserLoginResponse>() {
@Override
public void onResponse(Call<UserLoginResponse> call, Response<UserLoginResponse> response) {
Toast.makeText(LoginActivity.this, "Success", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<UserLoginResponse> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
Upvotes: 1