【问题标题】:How to access of a especific element in the response of Retrofit如何在 Retrofit 的响应中访问特定元素
【发布时间】:2017-11-02 20:31:40
【问题描述】:

我正在使用 Retrofit 查询一个 API,答案是这样的

[
{
    "Id": "BT00",
    "Text": "Registrarme"
},
{
    "Id": "BT01",
    "Text": "Iniciar sesión"
},
{
    "Id": "BT02",
    "Text": "Siguiente"
},
{
    "Id": "BT03",
    "Text": "Si"
},
{
    "Id": "BT04",
    "Text": "No"
}
]

并且正文响应看起来像这样screenshot

此调用存储在 ArrayList 中。

@SerializedName("Id")
@Expose
private String id;
@SerializedName("Text")
@Expose
private String text;
//Getters&Setters

我的回答是,如何访问响应的元素?

我尝试了以下方法,但都不起作用

apptext_id.setText(response.body().get(0).toString());
Logger.d("Body %s", response.body().get(0).toString());
Logger.d("Body %s", response.body().get(0));

答案看起来像this

【问题讨论】:

    标签: java android arraylist retrofit2


    【解决方案1】:

    获取列表的第一个元素需要做的是:response.body().get(0).getText();

    如果您需要获得每个项,您需要:

    if (response.isSuccessful()) {
    
        List<AppTextModel> list_elements = response.body();
        for (AppTextModel item : list_elements) {
            Logger.d("Body %s", item.getText()); // print every text item in list
        }
    }
    

    你还需要在 POJO 类中:

    public class AppTextModel {
    
        @SerializedName("Id")
        @Expose
        private String id;
        @SerializedName("Text")
        @Expose
        private String text;
    
        //Getters&Setters
    
        public String getText() {
            return text; 
        }
    }
    

    【讨论】:

    • 很高兴我能帮上忙 ;)
    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2016-07-05
    相关资源
    最近更新 更多