gson 在不使用其他类的情况下对Json对象进行Retrofit入队解析

zlhcx6iw  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(190)

我有一些工作代码,可以解析从一个改型API get调用中得到的Json文件。但是,我目前这样做需要两个类(其中一个只是包含另一个的列表),如果我想知道是否可以用一个数据类来做这件事,下面会有更多的解释。

我拥有的:

  • 接口:*
  1. interface ApiInterface {
  2. @GET(value = "all_people.php")
  3. fun getAllPeople(): Call<People>
  4. }
  • 密码:*
  1. retrofit: ApiInterface = Retrofit.Builder()
  2. .addConverterFactory(GsonConverterFactory.create())
  3. .baseUrl(BASE_URL)
  4. .build()
  5. .create(ApiInterface::class.java)
  6. retrofit.getAllPeople().enqueue(object : Callback<People?> {
  7. override fun onResponse(call: Call<People?>, response: Response<People?>) {
  8. Log.d("First person", responce.body()!!.people[0])
  9. }
  10. override fun onFailure(call: Call<People?>, t: Throwable) {}
  11. })
  • 数据类别:*
  1. data class Person (
  2. val firstName: String,
  3. val lastName: String
  4. )
  5. data class People (
  6. val people: List<Person>
  7. )

"这很有效"
问题是,这需要一个额外的类(People)。这是因为我从API中返回了一个JSON对象(其中包含了我想要访问的JSON数组)。这是我在网上看到的解决方案,当我看到类似的场景时,然而,这个方法需要我为每个不同的API调用创建一个额外的类,其中只包含一个列表。这显然不是理想的。

**问题:**我的问题是,在消除类People的同时,我如何做到这一点?

"我想做的事情就像这样:"

  • 接口:*
  1. interface ApiInterface {
  2. @GET(value = "all_people.php")
  3. fun getAllPeople(): Call<List<Person>>
  4. }
  • 密码:*
  1. retrofit: ApiInterface = Retrofit.Builder()
  2. .addConverterFactory(GsonConverterFactory.create())
  3. .baseUrl(BASE_URL)
  4. .build()
  5. .create(ApiInterface::class.java)
  6. retrofit.getAllPeople().enqueue(object : Callback<List<Person>?> {
  7. override fun onResponse(call: Call<List<Person>?>, response: Response<List<Person>?>) {
  8. //The issue is here, because this is a Json object, and I am treating it like a list
  9. //Is there a way of access the Json array inside this Json object without creating the person class?
  10. Log.d("First person", responce.body()!![0])
  11. }
  12. override fun onFailure(call: Call<List<Person>?>, t: Throwable) {}
  13. })

但是,我无法确定如何“打开”Json对象以使其工作,因此得到以下错误代码:

9avjhtql

9avjhtql1#

我想到了一些有用的东西,但我不认为它是理想的。我没有使用内置的GsonConverter来改造,而是自己做。
在onResponse中我执行以下操作

  1. val peopleList = GsonBuilder()
  2. .create()
  3. .fromJson(response.body()!!.getAsJsonArray("people"), Array<Person>::class.java).toList()
  4. Log.d("First person", peopleList!![0])

我一点也不确定这是否比只拥有额外的数据类更好

相关问题