java - 如何在android中使用retrofit获取Json响应中的数组数据?

标签 java android retrofit retrofit2 jsonresponse

嘿,我得到了一个 json 响应,其中也包含字符串和数组,获取字符串工作正常,但当尝试获取数组类型数据时,它在工作室中出现错误。

{
"body": [
    {
       "customer": "erp touch",

      "description": [
        "ythn",
        "bgtr",
        "ythn"
    ]

  }
 ]
}

我能够获取客户,但无法进行描述,这是我用于描述的 pojo

@SerializedName("description")
private List<String> description = null;

public List<String> getDescription() {
    return description;
}

这就是我用来获取它的

 OrderListResponse orderListResponse = response.body().getBody();

 description_tv.setText(orderListResponse.getDescription()); // this line give error cannot resolve setText(java.util.list<java.lang.string>)

NOTE: Please do not get confused with response.body().getBody() because i haven't posted the complete response.

请告诉我如何获取这些数据,如有帮助,我们将不胜感激。

谢谢!!

编辑

嘿,实际上我和我的伙伴一起想出了我们如何在数组中显示这些数据,但我遇到了问题。

我想从 json 响应中获取这个描述数组,并在不同的 TextView 中显示它的不同元素。使用 ,

description_tv1.setText(orderListResponse.getDescription().get(0));
description_tv2.setText(orderListResponse.getDescription().get(1));
description_tv3.setText(orderListResponse.getDescription().get(2));

将解决问题,但数组中的元素可能会有所不同 对于任何数字,所以实际上我不知道应该使用多少个文​​本 View ,这是真正的问题。

有什么方法可以根据我的问题创建 TextView 吗?

任何建议或帮助将不胜感激。

再次感谢!

最佳答案

setText 不接受列表作为参数。您可以尝试使用 .join 像这样加入列表中的项目

字符串结果 = TextUtils.join(", ", orderListResponse.getDescription());

然后你可以调用setText(result)

<小时/>

提示:请确保首先检查结果和描述!

List<String> description = orderListResponse.getDescription();
if (description == null) { // show error }

关于java - 如何在android中使用retrofit获取Json响应中的数组数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52969489/

相关文章:

Android -- 为什么我的应用程序使用大约 40MB 的缓存后台进程?

retrofit - OkHttpClient无法解析方法setCache

android - 选择根元素(又名键或信封)

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 使用 JavaRegex 或 Jsoup 解析 Html 标签

java - 如何从 Maven 3.0 插件获取本地存储库位置?

java - 将 ListView 中的复选框状态保存到 ArrayList 中

android - 如何在不需要 gmail 的情况下从电子邮件链接到 Android 应用程序?

android - 在嵌套的 JSON 对象中使用 Retrofit

java - 如何在Java中实现固定大小的 "list"?