java—如何通过改造android发布请求和获取响应(嵌套json)

ncgqoxb0  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(294)

下面是嵌套的json请求

{
"user": {
    "email": "123@mail.com",
    "password": "12345678"
    }
}

下面是嵌套的json响应

{
    "data": {
        "renew_token": "e994c4d2-d93b-47e8-ab5f-9090b823f249",
        "token": "419fff70-b1ee-4ea7-b636-ddbec6346794"
    }
}

我可以发布请求,但我很难在相同的过程中编写响应代码
当前我的界面

public interface JsonApi {

    @POST("session")
    Call<RootUser> userLogin(@Body RootUser rootUser);
}

请求模型

public class User{
    public String email;
    public String password;
}

public class RootUser{
    public User user;
}

api调用

private void userLogin(){
        String email = etloginemail.getText().toString();
        String password = etloginpassword.getText().toString();

        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://the-digest-app.herokuapp.com/api/")
                                        .addConverterFactory(GsonConverterFactory.create())
                                        .build();

        JsonApi jsonApi = retrofit.create(JsonApi.class);

        User user = new User(email, password);
        RootUser rootUser = new RootUser(user);

        Call<RootUser> call = jsonApi.userLogin(rootUser);

        call.enqueue(new Callback<RootUser>() {
            @Override
            public void onResponse(Call<RootUser> call, Response<RootUser> response) {
                Toast.makeText(LoginActivity.this, "Success", Toast.LENGTH_LONG).show();
                         }

            @Override
            public void onFailure(Call<RootUser> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_LONG).show();
            }
        });

    }

如何定义get response函数?如果我做错了什么,请告诉我!

9gm1akwq

9gm1akwq1#

您应该再创建一个pojo来响应

public class LoginResponse{
    @SerializedName("renew_token")
    public String renewToken;
    @SerializedName("token")
    public String token;
}

public class UserLoginResponse{
    public LoginResponse data;
}

你的改装界面应该是

public interface JsonApi {

    @POST("session")
    Call<UserLoginResponse> userLogin(@Body RootUser rootUser);
}

以及你的呼叫执行

call.enqueue(new Callback<UserLoginResponse>() {
            @Override
            public void onResponse(Call<UserLoginResponse> call, Response<UserLoginResponse> response) {
                Toast.makeText(LoginActivity.this, "Success", Toast.LENGTH_LONG).show();
                         }

            @Override
            public void onFailure(Call<UserLoginResponse> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_LONG).show();
            }
        });

相关问题