2

My REST API response looks like this:

{
"message": "OK",
"data": {
    "api_token": "1dwdafg45567fsf",
    "name": "Albert",
    "second_name": "Ferbs"
 }
}

My Interface is:

@POST("api/login")
Call<LoginResponse> loginUser(@Body LoginRequest loginRequest);

I want to get a value from "api_token". My LoginResponse is:

public class LoginResponse implements Serializable {
private String api_token;

public String getApi_token() {
    return api_token;
}

public void setApi_token(String api_token) {
    this.api_token= api_token;
}
}

But loginResponse.getApi_token() returns me "null". What should i do?

beliy
  • 21
  • 8
  • There seems to be a missing link. How do you parse the `JSON` returned by your API in the `LoginResponse`? Unless this is done, `api_token` is not initialized (`null`). – Johannes Apr 10 '21 at 12:58
  • Well, for example, if i will ask for getData, where Data is an object, i will recieve smth like: api_token=dawdawdawdaw,name=name,second_name=secon_name. I just want to know how to get only api token/name/second_name from this. So i dont know how to parse it – beliy Apr 10 '21 at 13:15
  • 1
    Have a look e.g. here: https://stackoverflow.com/questions/9605913/how-do-i-parse-json-in-android – Johannes Apr 10 '21 at 14:48
  • Got nothing working here. I think that Retrofit should have its own methods for parsing and answer( – beliy Apr 10 '21 at 16:03
  • 1
    Yes, see e.g. here https://www.geeksforgeeks.org/json-parsing-in-android-using-retrofit-library/ Please add more information of what was not working, otherwise we are nto bale to help here. – Johannes Apr 10 '21 at 16:09
  • Just got nothing after using JSONArray or JSONObject. I think that my problem is in Interface or in LoginResponse. Mb i have to add a class Data, or set Call as list? – beliy Apr 10 '21 at 16:30
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230974/discussion-between-beliy-and-johannes). – beliy Apr 10 '21 at 16:43

1 Answers1

2

you should do as below:

first create Data class parser

public class Data implements Serializable {
       @SerializedName("api_token")
       private String api_token;

       public String getApi_token() {
       return api_token;
      }

}

then change your loginResponse class :

public class LoginResponse implements Serializable {

@SerializedName("message")
private String message;
@SerializedName("data")
private Data data;

public String getMessage() {
    return message;
}

public String getData() {
    return data;
}

}

then you can call your method

response.getData().getApi_token();
behrad
  • 1,228
  • 14
  • 21