如果响应与帖子类不同,如何从帖子请求中获得响应

我正在使用改造通过 api 将登录详细信息传递到我的服务器。api 的发布请求只接受电子邮件和密码,但响应返回与 POJO 类包含的内容不同的 Json 格式。我如何处理 api 响应?


我尝试将响应作为 JSONObject 返回以帮助从 api 获取 Json,但它不起作用。API 返回包含用户名和登录令牌的成功 json。


    Call<LoginPost> call = apiLink.loginUser(useremail, userpassword);


    call.enqueue(new Callback<LoginPost>() {

        @Override

        public void onResponse(Call<LoginPost> call, Response<LoginPost> response) {

            if(!response.isSuccessful()){

                String code = Integer.toString(response.code());

                Toast.makeText(LoginPage.this, code, Toast.LENGTH_LONG).show();

            }

            else {

             LoginPost postResponse = response.body();


             Log.e("viewResponse", 

                   postResponse.getSuccessResponse().toString());


               return;

            }

        }


        @Override

        public void onFailure(Call<LoginPost> call, Throwable t) {

            Log.e("error in createNewUser",  t.getMessage());

        }

    });

帖子类:


@SerializedName("email")

String userEmail;



@SerializedName("password")

String userPassword;


public JSONObject getSuccessResponse() {

    return successResponse;

}


@SerializedName("success")

JSONObject successResponse;



public String getUserEmail() {

    return userEmail;

}



public String getUserPassword() {

    return userPassword;

}


蛊毒传说
浏览 57回答 1
1回答

烙印99

在进行 Retrofit 调用时,不应为 Request 使用 POJO 类,而应使用与 Response 匹配的 POJO 类。因为这只是使用参数进行调用,所以您可能甚至不需要 Request 对象,但拥有一个也没有坏处。您的代码看起来像这样:Call<LoginResponse> call = apiLink.loginUser(useremail, userpassword);call.enqueue(new Callback<LoginResponse>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {&nbsp; &nbsp; &nbsp; &nbsp; if(!response.isSuccessful()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String code = Integer.toString(response.code());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(LoginPage.this, code, Toast.LENGTH_LONG).show();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;LoginResponse postResponse = response.body();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Log.e("viewResponse",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;postResponse.getSuccessResponse().toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onFailure(Call<LoginResponse> call, Throwable t) {&nbsp; &nbsp; &nbsp; &nbsp; Log.e("error in createNewUser",&nbsp; t.getMessage());&nbsp; &nbsp; }});为了进一步解释发生了什么,当你创建你的参数化调用时,你告诉 Retrofit 使用哪个对象来解析响应,(如果你想使用一个对象作为发布主体数据,你需要以不同的方式声明你的 API):&nbsp;@POST("auth/login")&nbsp;Call<LoginResponse> loginUser(@Body LoginPost body);&nbsp;Call<LoginResponse> call = apiLink.loginUser(LoginPost body);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java