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

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

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

我拥有的:

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

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

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

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

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

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

9avjhtql

9avjhtql1#

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

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

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

相关问题