首页 > 解决方案 > 如何使用android中的改造在Json响应中获取数组数据?

问题描述

嘿,我得到了一个包含字符串和数组的 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>)

注意:请不要与 response.body().getBody() 混淆,因为我没有发布完整的回复。

请告诉我如何获取这些数据,任何帮助都会很明显。

谢谢!!

编辑

嘿,实际上我和我的伙伴想出了我们想如何在数组中显示这些数据,我对此有疑问。

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

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

将解决问题,但数组中的元素可以变化到任意数量,所以实际上我不知道我应该使用多少个文​​本视图,这是真正的问题。

有什么方法可以根据我的问题创建文本视图?

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

再次感谢 !

标签: javaandroidretrofitretrofit2jsonresponse

解决方案


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

String result = TextUtils.join(", ", orderListResponse.getDescription());

然后你可以打电话setText(result)


只是一个提示:确保您首先检查结果和描述!

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

推荐阅读