【问题标题】:How to get array data in Json response using retrofit in android?如何使用android中的改造在Json响应中获取数组数据?
【发布时间】:2018-10-24 12:50:38
【问题描述】:

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

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

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

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

再次感谢!

【问题讨论】:

  • 当然,如果您尝试将List&lt;String&gt; 设置为text view,它会给出错误,这需要string
  • 试试这个并检查description_tv.setText(orderListResponse.getDescription().get(0));
  • 这会给我第一个元素

标签: java android retrofit retrofit2 jsonresponse


【解决方案1】:

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

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

然后你可以拨打setText(result)


提示:确保先对结果和描述进行空检查!

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

【讨论】:

  • 我可以对结果变量进行空值检查,因为我是来自 response.body() 的描述
  • 嗯,这就是我一直在寻找的答案,但请帮我解决这个问题
  • 嘿,我编辑了我的问题,遇到了类似的问题,你可以去检查一下吗>
  • 您不能只编辑带有新问题的提交。请在 StackOverflow 上发新帖
【解决方案2】:

尝试在 TextView 中使用 append

 for (String s : orderListResponse.getDescription()){
                description_tv.append(s);

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 2016-03-23
    • 2020-06-06
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多