【问题标题】:Iterate through Retrofit response迭代改造响应
【发布时间】:2015-11-03 05:26:04
【问题描述】:

我正在为我的 Android 应用程序使用 Retrofit,这样称呼它:

RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(BASE_URL)
        .build();

ApiEndpointInterface apiService = restAdapter.create(ApiEndpointInterface.class);

apiService.getFeed(9, new Callback<Post>() {

    @Override
    public void success(Post post, Response response) {
        // loop
    }

    @Override
    public void failure(RetrofitError retrofitError) {
        retrofitError.printStackTrace();
    }
});

JSON 格式如下:

{
    "success":true,
    "data":[
        {
            "id":"1",
            "user_id":"2",
            "message":"Hello, world!"
        },
        {
            "id":"2",
            "user_id":"1",
            "message":"Another hello!"
        }
    ]
}

如何遍历每个项目,例如,将其消息打印到控制台?每个项目都属于Post 模型:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Post {
    public String id;
    public String userId;
    public String message;

    public String getMessage() {
        return message;
    }
}

【问题讨论】:

  • 你能添加你的模型类吗?根据你的模型课,我会帮​​助你。
  • 编辑了原始帖子以包含模型。

标签: android android-fragments android-activity android-studio retrofit


【解决方案1】:

您的 Main 模型类如下所示。

public class Post {
        private String success;
        private List<data> data;

        public List<data> getData() {
            return data;
        }
    }

这是你的数据类。你需要创建另一个类来检索 json arary(对你来说是数据。)

public class data {
    public String id;
    public String userId;
    public String message;

    public String getMessage() {
        return message;
    }
}

apiService.getFeed(9, new Callback<Post>() {

    @Override
    public void success(Post post, Response response) {
        post.getData().getPositoin(YourPosition).getMessage(); //or you can use for loop

    }

    @Override
    public void failure(RetrofitError retrofitError) {
        retrofitError.printStackTrace();
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2018-11-04
    相关资源
    最近更新 更多