【问题标题】:How to get JSON Array without object key using retrofit如何使用改造获得没有对象键的 JSON 数组
【发布时间】:2021-10-21 16:53:50
【问题描述】:

我在加载想从下面的 JSON 中检索 url 数据时遇到问题

{
     "status": "success",
     "message": "This is a message",
     "item":{
         "id":"1",
         "video":{
             "url" : [
                 "https://url1.com",
                 "https://url1.com",
                 "https://url1.com"
             ]
          }
     }
}

响应数据

public class ResponseData {

    @SerializedName("status")
    private String status;
    @SerializedName("message")
    private String message;
    @SerializedName("item")
    private Item item;

    //Getters
}

物品

public class Item {
   
   @SerializedName("id")
   private String id;
   @SerializedName("video")
   private Video video;
   
   //Getters
}

视频

public class Video { 

   @SerializedName("url")
   private List<String> urlList;
   
   //Getters
}

在此之后我应该怎么做才能获取每个 URL 并将其应用到 Retrofit onResponse 中?

 @Override
 public void onResponse(@NonNull Call<ResponseData> call, @NonNull Response<ResponseData> response) {
     if (response.isSuccessful()) {
         ResponseData resp = response.body();

         //For the call I want results like the method below
         DataFromServer d = new DataFromServer();
         d.url = resp.getItem().getVideo().getUrlList().getUrl1(); // I want it like this
     }
 }

【问题讨论】:

  • 您到底想要什么?您正在收到回复,是否要返回网址?
  • 我想一一获取url,但是Video Class中的getUrlList()方法因为是List数据类型所以不能调用,而我想获取那个方法然后调用getUrl1() 方法在改造响应中调用它
  • 假设数据被正确解析然后你可以使用getUrlList().get(1);
  • 没有让你正确,但如果你想要每个 url 一个一个然后使用 for 循环 并使用索引号。像这样getUrlList().get(i);这里i表示索引号。
  • 我试过这个 getUrlList().get(i);但是得到的值总是null

标签: java android json retrofit


【解决方案1】:
    resp.getItem().getVideo().getUrlList().forEach((url) -> {
       Log.i("url", url) // you can get each url here
     }
    );

您基本上是从服务器获取列表。

您不需要密钥即可访问它们。您可以将它们存储在列表中,也可以这样做

list.get(0) - 用于第一个网址

list.get(1) - 第二个网址

等等。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-07-13
  • 2016-11-02
  • 2017-05-12
  • 2016-02-13
  • 1970-01-01
  • 2020-01-29
  • 2017-08-02
  • 1970-01-01
相关资源
最近更新 更多