RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1446694
Accepted
user515715
user515715
Asked:2022-09-08 13:44:25 +0000 UTC2022-09-08 13:44:25 +0000 UTC 2022-09-08 13:44:25 +0000 UTC

从具有多层的 Json 中使用 Retrofit 获取数据

  • 772

有json:

{
  "success": true,
  "result": {
    "current_page": 1,
    "data": [
      {
        "id": 1,
        "name": "Hayley O'Keefe",
        "description": "Eveniet sed exercitationem distinctio voluptatum qui magnam ratione et soluta itaque explicabo laborum nemo mollitia et veniam aut sed voluptatibus at sequi aut consequatur labore quod vel iusto...",
        "date": "1991-03-24"
      },
      {
        "id": 2,
        "name": "Terry Schaefer",
        "description": "Consectetur explicabo porro quis debitis itaque corrupti eius beatae aliquid facilis ea quo soluta porro est facere ut quia sit provident suscipit ut eos inventore est aperiam nostrum sit reprehenderit...",
        "date": "1988-08-27"
      },
      {
        "id": 3,
        "name": "Jude Sporer DVM",
        "description": "Explicabo illum et excepturi doloremque quidem laboriosam excepturi quae fugit nostrum et enim enim libero vitae sit perspiciatis quis consequatur eum ratione sequi doloribus voluptatem velit commodi...",
        "date": "1984-02-14"
      },
      {
        "id": 4,
        "name": "Prof. Leola Rogahn",
        "description": "Quia iste id sint repellat debitis illo ex et commodi et repellendus consequuntur consequatur modi molestiae...",
        "date": "2005-10-29"
      },
      {
        "id": 5,
        "name": "Jaylon VonRueden",
        "description": "Aspernatur sit iusto enim asperiores est quis autem tempore fuga qui omnis inventore nostrum ab debitis ducimus voluptatem quia ipsa placeat molestiae dolores doloremque ipsa tempore vero...",
        "date": "2019-04-09"
      },
      {
        "id": 6,
        "name": "Margie Kertzmann",
        "description": "Aut itaque non expedita laborum vero inventore ipsa commodi nobis accusantium hic aspernatur ab fuga molestiae dignissimos eaque voluptatum sapiente totam et exercitationem dolorem qui tempora...",
        "date": "2020-12-10"
      },
      {
        "id": 7,
        "name": "Monserrat Kulas",
        "description": "Eum sunt eius ab sit qui soluta quisquam quam qui vel eaque exercitationem error necessitatibus aspernatur qui optio et qui doloribus necessitatibus aut et reprehenderit doloremque non et dolor...",
        "date": "1976-02-25"
      },
      {
        "id": 8,
        "name": "Dr. Filomena Pagac PhD",
        "description": "Dolores nostrum fugiat incidunt et sapiente sunt dolores et illo magnam repudiandae dolores et voluptas inventore error iusto rem ut aperiam quo similique eveniet ut culpa veniam recusandae pariatur delectus...",
        "date": "1984-02-05"
      },
      {
        "id": 9,
        "name": "Camden Armstrong",
        "description": "Est aspernatur tempore necessitatibus rerum aut placeat incidunt molestias molestiae voluptatem at non vitae...",
        "date": "1980-04-05"
      },
      {
        "id": 10,
        "name": "Jade Mosciski",
        "description": "Quis odio ut nihil non eum accusamus voluptatem minus deleniti non tempora eligendi ullam consequatur dignissimos ....",
        "date": "1978-04-05"
      }
    ],
    "first_page_url": "http://candidate.scid.ru/api/books?page=1",
    "from": 1,
    "last_page": 10,
    "last_page_url": "http://candidate.scid.ru/api/books?page=10",
    "links": [
      {
        "url": null,
        "label": "« Previous",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=1",
        "label": "1",
        "active": true
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=2",
        "label": "2",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=3",
        "label": "3",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=4",
        "label": "4",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=5",
        "label": "5",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=6",
        "label": "6",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=7",
        "label": "7",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=8",
        "label": "8",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=9",
        "label": "9",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=10",
        "label": "10",
        "active": false
      },
      {
        "url": "http://candidate.scid.ru/api/books?page=2",
        "label": "Next »",
        "active": false
      }
    ],
    "next_page_url": "http://candidate.scid.ru/api/books?page=2",
    "path": "http://candidate.scid.ru/api/books",
    "per_page": 10,
    "prev_page_url": null,
    "to": 10,
    "total": 100
  },
  "error": null
}

如果你把它分解成模型,你会得到以下层次结构(如果我没有混淆任何东西):

在此处输入图像描述

模型本身:

Pagination:

data class Pagination(
    val error: Any,
    val result: Result,
    val success: Boolean
)

Result:

data class Result(
    val current_page: Int,
    val `data`: List<Data>,
    val first_page_url: String,
    val from: Int,
    val last_page: Int,
    val last_page_url: String,
    val links: List<Link>,
    val next_page_url: String,
    val path: String,
    val per_page: Int,
    val prev_page_url: Any,
    val to: Int,
    val total: Int
)

Data:

data class Data(
    val date: String,
    val description: String,
    val id: Int,
    val name: String
)

Link:

data class Link(
    val active: Boolean,
    val label: String,
    val url: String
)

我需要从中获取数据Data

问题来了。由于我需要在层次结构中更高的模型中“包装”两次Data,因此我为此目的创建了以下类:

PaginationApiModel:

class PaginationApiModel {

    @SerializedName("result") @Expose
    val result: ResultApiModel? = null

}

ResultApiModel:

class ResultApiModel {

    @SerializedName("data") @Expose
    val data: ArrayList<Data>? = null

}

但是我需要从 Json 获取一组数据,这就是为什么我不太明白ApiDataSourceIMPL如果我将它替换为ArrayList<Data>如何实现这个类片段PaginationApiModel:

        for (audit in loadNameList) {

            audit.id?.let {
                PaginationLocalModel(
                    it,

                    audit.name.toString(),
                    audit.date.toString(),
                    audit.description.toString(),

                )
            }?.let {
                dataSource.insert(
                    it
                )
            }

这就是我的班级现在的样子ApiDataSourceIMPL:

class ApiDataSourceIMPL (private val dataSource: RDDataSource):
    ApiDataSource {

    override fun startMigration (context: Context) {

    val call = ApiClient.instance?.api?.loadApi()
    call?.enqueue(object: Callback <ArrayList<Data>>
     {
        override fun onResponse(
            call: Call<ArrayList<Data>>,
            response: Response<ArrayList<Data>>
        ) {

            Log.d("ApiDataSource", "onResponse status: ${response.code()}")

            var loadNameList: ArrayList<Data>? = null

           // loadNameList?.clear()

            loadNameList = (response.body() as ArrayList<Data>?)!!
                  

            for (audit in loadNameList) {

                audit.id?.let {
                    PaginationLocalModel(
                        it,

                        audit.name.toString(),
                        audit.date.toString(),
                        audit.description.toString(),

                    )
                }?.let {
                    dataSource.insert(
                        it
                    )
                }

            }

            Toast.makeText(context, "ЗАГРУЗКА", Toast.LENGTH_SHORT).show()
        }

        override fun onFailure(call: Call <ArrayList<Data>>
   
                               , t: Throwable) {
            t.printStackTrace()
            Toast.makeText(context, "ОШИБКА! ВКЛЮЧИТЕ ИНТЕРНЕТ!", Toast.LENGTH_SHORT).show()
            Log.e("ApiDataSource2", "onFailure", t)
        }
    })

}

}

本地数据库模型:

@Entity(tableName = "pagination_table")
class PaginationLocalModel (

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "date")
    val date: String,

    @ColumnInfo(name = "description")
    val description: String

)

本地数据库:

@Database(entities = [PaginationLocalModel::class], version = 1)
abstract class ReceiveDataDB : RoomDatabase() {

    abstract val nameListDao : NameListDao
    abstract val descriptionDao : DescriptionDao

}
android
  • 0 0 个回答
  • 0 Views

0 个回答

  • Voted
  1. Best Answer
    woesss
    2022-09-08T14:36:19Z2022-09-08T14:36:19Z

    带有循环的片段没有改变,链接到列表的活动发生了变化:

    loadNameList = response.body().result.data
    

    PS而不是类,Data您可以立即使用json模型PaginationLocalModel-它们是相同的

    • 0

相关问题

  • 来自片段的列表落后于 BottomNavigationView

  • 无法将变量从 Activity 传递到 Fragment

  • 构建与完成的片段略有不同的片段的最佳方法是什么?

  • 如何更改来自服务器的响应中的日期格式?

  • 谷歌地图在应用程序的发布版本中不起作用

  • 材料设计按钮。单击按钮上的可选区域!

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5