Lending Square
Lending Square

Reputation: 201

Get token from Server Response in JSON

I send a post request to a server via the help of Retrofit but i want to get a value from a token when the server sends a response back. This is how i send my post request and onSuccess i want to receive the token. My problem here is that i don't know to retrieve the token from the server response. Kindly help here.

public void loginUser(String userName, String userPassword, Boolean userRememberMe) {

    mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<Login>() {
        @Override
        public void onResponse(Response<Login> response, Retrofit retrofit) {
            if(response.isSuccess()) {
                //save token here
                Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                startActivity(intent);
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            Log.e(TAG, "Unable to Login");
        }
    });
}

This is the response i get from the server

{
 "total": 0,
 "data": {
"id": "348680c7-d46b-4adc-9be0-89a1d1a38566",
"username": "0242770336",
"name": "name",
"phoneNumber": "063546345",
"email": "[email protected]",
"dateOfBirth": null,
"image": null,
"gender": "",
"idTypeId": null,
"idType": null,
"idNumber": null,
"idExpiryDate": null,
"idVerified": false,
"cityId": null,
"city": null,
"residentialAddress": null,
"latitude": 0,
"longitude": 0,
"createdAt": "2017-08-14T17:45:16.24Z",
"role": {
  "id": 2,
  "name": "User",
  "privileges": [
    ""
  ]
},
"token": "jNK_DGszYOMEpPOFoRGjuyJ5KX9kaJQKCl3cujlHoXklCS8Ij6b-QBmhv0jVwVC54KcNXkzyM62xpswqcjo9Ajf-n-rWzSaIoiYNglaXhtPspziZ0PcTKzTMAvw8si3A7BlcD98M-IjIxYjxieVYAPWVtcvomWi"
},

"message": "Login Successfull",
"success": true
}

This is my Login Model

public class Login {

@SerializedName("userName")
@Expose
private String userName;
@SerializedName("password")
@Expose
private String password;
@SerializedName("rememberMe")
@Expose
private Boolean rememberMe;

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Boolean getRememberMe() {
    return rememberMe;
}

public void setRememberMe(Boolean rememberMe) {
    this.rememberMe = rememberMe;
}

}

Upvotes: 0

Views: 9167

Answers (5)

Chandan Bhandari
Chandan Bhandari

Reputation: 217

There are two approaches to this.

method 1 :use JsonObject

mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<JsonObject>() {
    @Override
public void onResponse(Response<JsonObject> response, Retrofit retrofit) {
       if(response.isSuccess()) {
         try {

           String token=response.body().get("data").get("token");
        } catch (JSONException e) {
              e.printStackTrace();
         }
Intent intent = new Intent(LoginActivity.this,ProfileActivity.class);
startActivity(intent);
    }
}
}

method 2: you can use http://pojo.sodhanalibrary.com/ to convert your response to POJO. now add it to your project and let's name it ResponseData.class and get token using getter method by doing to following changes

mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<ResponseData>() {
    @Override
    public void onResponse(Response<ResponseData> response, Retrofit retrofit) {
        if(response.isSuccess()) {
            //save token here
String token =response.getData().getToken();

            Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onFailure(Throwable throwable) {
        Log.e(TAG, "Unable to Login");
    }
});

Upvotes: 3

R7G
R7G

Reputation: 1060

for this you need to first understand that this response is in Json format you need to first create the Json object from the response you get from server . for better understanding https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ http://www.json.org/ and code to get that response.

try{
       JSONObject jsonObject = new JSONObject(response);
        String token = jsonObject.getJSONObject("data").getString("token");
}
catch(JSONException e){
e.printstacktrace();
}

Upvotes: 0

M.Waqas Pervez
M.Waqas Pervez

Reputation: 2430

You can use Gson to convert you json to a java POJO class. However if you just want to get the token field you can use it like this:

public void onResponse(Response<Login> response, Retrofit retrofit) {
        if(response.isSuccess()) {
             try {
        JSONObject ob = new JSONObject(response.body());
        String token = ob.getJSONObject("data").getString("token");

    } catch (JSONException e) {
        e.printStackTrace();
    }
            Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
            startActivity(intent);
        }
    }

Upvotes: 0

KeLiuyue
KeLiuyue

Reputation: 8237

Try this.

Use optBoolean() method and optString() method

try {
        JSONObject jsonObject = new JSONObject(response);
        boolean success = jsonObject.optBoolean("success");
        if (success) {
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.optString("token");
        } else {
            Log.e("message", "failure");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

Upvotes: 0

Nouman Ch
Nouman Ch

Reputation: 4121

Convert the response string into JSONObject and then again get the JSONObject for data and in data you can find your token object.

JSONObject  object  = new JSONObject(response);
JSONObject dataObject = object.getJSONObject("data");
String token = dataObject.getString("token");
Log.i("TAG","token is "+token);

Upvotes: 0

Related Questions