如果我有一个 JsonArray 和 JsonArray 中的动态 JsonObject,如何创建 pojo 类?

问题描述 投票:0回答:1

Android上使用Retrofit调用api时出现以下问题

响应json

[
  {
    "test1": 10,
    "test2": 20,
    "test3": 37,
    "test_list": [
      {
        "id": 11,
        "content": "AAA"
      }
    ]
  },

  {
    "test1": 23,
    "test2": 37,
    "test3": 62,
    "test_list": [
      {
        "id": 13,
        "content": "AAA"
      }
    ]
  },
  
  [
    {
      "test1": 33,
      "test2": 17,
      "test3": 67,
      "test_list": [
        {
          "id": 15,
          "content": "BBB"
        }
      ]
    }
  ]
]

JsonArray 中有一个动态 JsonObject

//dynamic
{
    "test1": 23,
    "test2": 37,
    "test3": 62,
    "test_list": [
      {
        "id": 13,
        "content": "AAA"
      }
    ]
  }

如果只有这部分存在的话,可以这样解决,但是同时存在一个JsonArray,并且里面的JsonObject的格式和外面的JsonObject是一样的

//Impossible because of JsonArray
data class Response(
    val data : List<POJO>
)

响应json格式无法更改如果有人知道答案,请帮忙。谢谢你

android json dynamic retrofit2 android-json
1个回答
0
投票

您可以结合使用 Kotlin 数据类和一些手动解析。由于 JSON 数组内部的结构可能会发生变化,因此您需要使用自定义反序列化器来处理动态 JSON 对象。

首先,为 JSON 结构创建数据类:

data class ResponseItem(
    val test1: Int,
    val test2: Int,
    val test3: Int,
    val test_list: List<TestListItem>
)

data class TestListItem(
    val id: Int,
    val content: String
)

现在,创建一个自定义反序列化器来处理 JSON 数组中的动态 JSON 对象。您可以使用 Gson 来实现此目的。将以下扩展函数添加到您的代码中:

import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type

class ResponseDeserializer : JsonDeserializer<ResponseItem> {
    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): ResponseItem {
        val jsonObject = json?.asJsonObject ?: throw JsonParseException("Invalid JSON")

        // Extract the fields you know exist
        val test1 = jsonObject.getAsJsonPrimitive("test1").asInt
        val test2 = jsonObject.getAsJsonPrimitive("test2").asInt
        val test3 = jsonObject.getAsJsonPrimitive("test3").asInt
        val testList = context?.deserialize<List<TestListItem>>(
            jsonObject.getAsJsonArray("test_list"),
            object : TypeToken<List<TestListItem>>() {}.type
        )

        // Create the ResponseItem object
        return ResponseItem(test1, test2, test3, testList ?: emptyList())
    }
}

现在,您可以在 API 接口中将 Retrofit 与此自定义解串器一起使用:

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

interface ApiService {
    @GET("your/api/endpoint")
    fun getResponse(): Call<List<ResponseItem>>
}

// Create a Retrofit instance with Gson and the custom deserializer
val retrofit = Retrofit.Builder()
    .baseUrl("your_base_url")
    .addConverterFactory(GsonConverterFactory.create(GsonBuilder().registerTypeAdapter(ResponseItem::class.java, ResponseDeserializer()).create()))
    .build()

// Create an instance of your ApiService
val apiService = retrofit.create(ApiService::class.java)

// Make the API call
val call = apiService.getResponse()
val response = call.execute()

if (response.isSuccessful) {
    val responseBody = response.body()
    // Handle the response as a list of ResponseItem objects
} else {
    // Handle the error
}

通过这种方式,Retrofit 和 Gson 可以用于反序列化 JSON 响应到 JSON 数组中的动态 JSON 对象。

© www.soinside.com 2019 - 2024. All rights reserved.