从JSON服务器响应中获取令牌
问题描述:
我通过Retrofit向服务器发送了一个post请求,但是当服务器发回响应时,我想从令牌获取一个值。这是我如何发送我的帖子请求和onSuccess我想要接收令牌。我的问题在于,我不知道从服务器响应中检索令牌。请在这里帮忙。从JSON服务器响应中获取令牌
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");
}
});
}
这是我从服务器获得响应
{
"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
}
这是我的登录模式
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;
}
}
答
有两种方法。
方法1:使用的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);
}
}
}
方法2: 可以使用http://pojo.sodhanalibrary.com/对POJO您回应转换。现在把它添加到您的项目,让我们将其命名为ResponseData.class并获得令牌使用getter方法从做以下的第一选项更改
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");
}
});
答
转换的响应串入JSONObject
,然后再得到JSONObject
的数据和数据可以找到你的令牌对象。
JSONObject object = new JSONObject(response);
JSONObject dataObject = object.getJSONObject("data");
String token = dataObject.getString("token");
Log.i("TAG","token is "+token);
答
试试这个。
使用optBoolean()
方法和optString()
方法
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();
}
答
您可以使用Gson
你json
转换为一个Java POJO类。不过,如果你只是想获得令牌字段,你可以使用它像这样:
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);
}
}
答
为此,你需要先了解这种反应是JSON格式 您需要首先从响应创建JSON对象你从服务器获得。为更好地理解https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ http://www.json.org/ 和代码来获得该响应。
try{
JSONObject jsonObject = new JSONObject(response);
String token = jsonObject.getJSONObject("data").getString("token");
}
catch(JSONException e){
e.printstacktrace();
}
如果回调是在登录模式排队,我将有一个错误。你在这种情况下建议我做什么。 –
我的请求模型与我的响应模型不同。检查我更新的问题。 –
回调将响应模型作为参数,因此您无法在其中使用登录模型,因为您的响应与响应不同。你需要改变的是你的改造请求应该返回调用或调用而不是调用 –