You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit实现登录时如何正确获取JSON响应并判断登录状态

如何用Retrofit正确解析登录接口的JSON响应并判断登录状态

看起来你现在的问题核心是没有用对应的实体类来接收接口返回的JSON,而是直接用了ResponseBody,导致无法直接获取success字段。我来一步步帮你修正代码,实现正确的解析和登录判断:

第一步:创建对应JSON结构的实体类

首先,我们需要定义一个和接口返回JSON完全匹配的实体类LoginResponse,这样Gson转换器就能自动帮我们把JSON转换成Java对象:

public class LoginResponse {
    // 注意字段名要和JSON里的键完全一致,或用@SerializedName注解指定映射关系
    private int success;
    private String customer_id;
    private String customer_group_id;
    private String email;

    // 生成对应的Getter方法
    public int getSuccess() {
        return success;
    }

    public String getCustomerId() {
        return customer_id;
    }

    public String getCustomerGroupId() {
        return customer_group_id;
    }

    public String getEmail() {
        return email;
    }
}

第二步:修改你的LoginApi接口

把接口方法的返回类型从Call<ResponseBody>改成Call<LoginResponse>,这样Retrofit就知道要把响应转换成我们的实体类:

public interface LoginApi {
    @GET("login.php")
    Call<LoginResponse> login(@Query("email") String email, @Query("password") String password);
}

第三步:修正登录方法的逻辑

现在我们可以在回调里直接获取实体类对象,轻松拿到success字段的值来判断登录状态:

private void attemptLogin(final String email, final String password) {
    Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("http://192.168.1.14/shop/api2/")
        .build();
    LoginApi service = retrofit.create(LoginApi.class);
    
    Call<LoginResponse> userCall = service.login(email,password);
    userCall.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            // 先判断请求是否成功(服务器返回2xx状态码)
            if (response.isSuccessful()) {
                LoginResponse loginResponse = response.body();
                // 确保响应体不为空,再判断success值是否为1
                if (loginResponse != null && loginResponse.getSuccess() == 1) {
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent in = new Intent(MainActivity.this, ProfileActivity.class);
                    // 还可以把用户ID等信息传递到下一个页面
                    in.putExtra("CUSTOMER_ID", loginResponse.getCustomerId());
                    startActivity(in);
                } else {
                    // success不为1,说明登录失败
                    Toast.makeText(MainActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                // 服务器返回非2xx状态码,比如404、500等
                Toast.makeText(MainActivity.this, "请求失败,状态码:" + response.code(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            // 网络请求失败,比如无网络、接口地址错误等
            Toast.makeText(MainActivity.this, "网络出错:" + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

为什么之前的代码会出错?

你之前用ResponseBody接收响应,它只是一个原始的响应体对象,不是解析后的JSON数据,所以resp.equals(1)这种判断完全不成立,而且也没有getStatus()方法——因为你没有定义对应的实体类,自然没法调用这样的getter方法。

用实体类配合Retrofit的Gson转换器是最规范的做法,它能帮我们自动完成JSON和Java对象的转换,避免手动解析JSON的繁琐和错误。

内容的提问来源于stack exchange,提问作者Ankush Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:57:09