[英]How to retrieve data from response? - Retrofit 2
来自服务器的响应如下:
{
success: true,
token: "someRandomToken"
}
如何从响应中检索token
?
我尝试遵循此处提供的解决方案,但无法在onResponse method
内的Call
添加泛型
编辑
这是我的方法
public void loginUser(final Context context, String url, String username, String passowrd, loginJson loginjson) {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
loginjson.setUsername(username);
loginjson.setPassword(passowrd);
Gson gson = new Gson();
String jsonFromForm = gson.toJson(loginjson);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, jsonFromForm);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("content-type", "application/json; charset=utf-8")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Failure!!");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()) {
if (context != null) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if(response.body() != null){
}
}
});
}
//
} else {
if (context != null) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.failed_to_login),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
}
在实现@Piyush Patel答案之后:我将Call
和Response
更改为retrofit2.Call<tokenRetrieved>
和retrofit2.Reponse<tokenRetrieved>
。 但Callback
在我enqueue
提示错误要求我履行其onResponse
和onFailure
方法
新手问题:我正在使用retrofit1
方法吗?
这是一个片段,显示了如何使用GSON来实现它
public class JsonResponse {
public String success;
public String token;
public JsonResponse(String success, String token) {
this.success = success;
this.token = token;
}
}
Call<JsonResponse> call = api.checkLevel(1);
call.enqueue(new Callback<JsonResponse>() {
@Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
if (response.isSuccessful()) {
JsonResponse jsonResponse=response.body();
}
}
@Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
}
});
凌空你可以这样做
试试这个代码
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
if ((object.getBoolean("success"))==true){
String Token=object.getString("token");
}else{
// enter else condition
}
} catch (JSONException e) {
e.printStackTrace();
// json Exception
}
}
从您的响应字符串创建一个JSONObject
并使用密钥token
获取该字符串
JSONObject json = new JSONObject(response);
json.getString("token");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.