如何从响应中检索数据? - 改造2

时间:2017-05-11 09:08:24

标签: java android gson retrofit2

来自服务器的响应如下:

{
    success: true,
    token: "someRandomToken"
}

如何从回复中检索token

我尝试按照here提供的解决方案,但我无法在onResponse Call内部method添加通用

修改

这是我的方法

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后答案: 我将CallResponse分别更改为retrofit2.Call<tokenRetrieved>retrofit2.Reponse<tokenRetrieved>。但我Callback中的enqueue提示错误,要求我实施其onResponseonFailure方法

新手问题:我使用的是retrofit1方法吗?!!

3 个答案:

答案 0 :(得分:3)

以下是一个片段,展示了如何使用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) {
            }
        });

答案 1 :(得分:1)

使用

  你可以这样做吗?

试试此代码

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

                    }

                }

答案 2 :(得分:0)

从您的回复字符串中创建JSONObject并获取包含密钥token的字符串

JSONObject json = new JSONObject(response);
json.getString("token");