在改造中使用post参数将项目显示到listview

时间:2018-03-10 17:18:53

标签: android json list post retrofit2

我一直在寻找改造教程几天。我必须使用改造在listview中显示项目。它是使用post参数完成的。在凌空中,如果我们有任何要发布的参数,我们将使用hashmap中的字符串请求。这里我有一个参数作为表单数据发布以获得响应。如何通过发布参数和接收响应来显示Listview中的项目。响应采用JSON格式。有人可以发布一些示例代码吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以定义一个改装对象,只需获取它的列表。

所以,让我们说你有一个对象User,它有一个id和一个名字。

您定义了一个RetrofitUser类

public class RetrofitUser {


    public static final String SERIALIZED_ID_NAME = "id_user";
    public static final String SERIALIZED_USERNAME = "name";

    @SerializedName(SERIALIZED_ID_NAME)
    private String mId;

    @SerializedName(SERIALIZED_USERNAME)
    private String mUserName;
}

SERIALIZED值是json键值的地方。

然后你会像这样定义一个api

public interface UserApi {

    @GET("/{yourParam}")
    Call<List<RetrofitUser>> getUserWithParam(@Path("yourParam") String param);
}

然后你会打电话给api -

mUsersService = retrofit.create(UserApi.class);
Call<List<RetrofitUser>> userCall = mUserService.getUserWithParam(yourParam);
        Response<List<RetrofitUser>> response;
        try {
            response = userCall.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (response.body() != null) {
             List<RetrofitUser> users = response.body();
        } else {
            throw new IllegalStateException("response body null");
        }

现在,假设您的JSON看起来像这样

[{id_user:1,name:“johnny”},{id_user:2,name:“jane”}]

你应该没问题,这是一个RetrofitUsers列表,一切都已满。