处理动态响应有时对象/数组在同一个关键的AndroidKotlin

vuktfyat  于 2023-02-24  发布在  Kotlin
关注(0)|答案(1)|浏览(106)

我收到了来自this api的响应,但在上有不同的响应

...
"value": [
    {
      "@unit": "C",
      "#text": "28"
    }
  ]

有时候

"value":
    {
      "@unit": "C",
      "#text": "28"
    }

我已经尝试从answer创建这个json适配器&模型类

object WeatherResponse {

    open class CuacaResponse{
        @SerializedName("Success")
        val success : Boolean = false
        val row : RowBean? = null
    }

    data class RowBean(
        val data : DataBean? = null
    )

    data class DataBean (
        val forecast : ForecastBean? = null
    )

    data class ForecastBean(
        val area : List<Area>? = null
    )

    data class Area(
        @SerializedName("@id")
        val id :String?="",
        @SerializedName("@description")
        val nama :String?="",
        val parameter : List<DataMain>?=null
        )

    data class DataMain(
        @SerializedName("@description")
        val namaData :String?="",
        @SerializedName("@id")
        val id :String?="",
        @SerializedName("timerange")
        val timeRange : List<TimeRangeItem>
    )

    data class TimeRangeItem(
        // sample data : 202107241800 => 2021-07-24-18:00
        @SerializedName("@datetime")
        val datetime : String,
        @JsonAdapter(ValueClassTypeAdapter::class)
        val value : ArrayList<ValueData>? = null,
    )

    data class ValueData(
        @SerializedName("@unit")
        val unit :String?="",
        @SerializedName("#text")
        val value :String?="",
    )

    class ValueClassTypeAdapter :
        JsonDeserializer<ArrayList<ValueData?>?> {
        override fun deserialize(
            json: JsonElement,
            typeOfT: Type?,
            ctx: JsonDeserializationContext
        ): ArrayList<ValueData?> {
            return getJSONArray(json, ValueData::class.java, ctx)
        }

        private fun <T> getJSONArray(json: JsonElement, type: Type, ctx:
        JsonDeserializationContext): ArrayList<T> {
            val list = ArrayList<T>()
            if (json.isJsonArray) {
                for (e in json.asJsonArray) {
                    list.add(ctx.deserialize<Any>(e, type) as T)
                }
            } else if (json.isJsonObject) {
                list.add(ctx.deserialize<Any>(json, type) as T)
            } else {
                throw RuntimeException("Unexpected JSON type: " + json.javaClass)
            }
            return list
        }
    }
}

我的翻新服务:

interface WeatherService {
    @GET("/api/cuaca/DigitalForecast-{province}.xml?format=json")
    suspend fun getWeather(
        @Path("province") provinceName: String? = "JawaTengah"
    ) : WeatherResponse.CuacaResponse?

    companion object {
        private const val URL = "https://cuaca.umkt.ac.id"
        fun client(context: Context): WeatherService {
            val httpClient = OkHttpClient.Builder()
            httpClient.apply {
                addNetworkInterceptor(
                    ChuckerInterceptor(
                        context = context,
                        alwaysReadResponseBody = true
                    )
                )

                addInterceptor { chain ->
                    val req = chain.request()
                        .newBuilder()
                        .build()
                    return@addInterceptor chain.proceed(req)
                }
                cache(null)
            }

            val gsonConverterFactory = GsonConverterFactory.create()

            return Retrofit.Builder()
                .baseUrl(URL)
                .client(httpClient.build())
                .addConverterFactory(gsonConverterFactory)
                .build()
                .create(WeatherService::class.java)
        }
    }
}

但我从日志请求中得到的结果是:

...
{
    "@datetime": "202108070000",
    "value": {
      "size": 4
    }
  },
  {
    "@datetime": "202108070600",
    "value": {
      "size": 4
    }
  },
  {
    "@datetime": "202108071200",
    "value": {
      "size": 4
    }
  }
...

值**返回IDK的大小,它应该从API返回单元和文本数组。2请任何人帮助我摆脱这个困境,提前感谢!

lx0bsm1f

lx0bsm1f1#

最后,我通过将JsonDeserializer更改为TypeAdapterFactory解决了这个问题,如this answer中所述

相关问题