使用 Ktor 客户端自定义通用响应

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

我正在尝试在内部通用类中编写一个自定义的“用于包装响应的 Ktor-client 转换器”,如下所示Medium Link

示例: 假设 api 给出以下响应,

    @Serializable
    @SerialName("DataResponseContainer")
    data class DataResponseContainer<out T>(val data: T?,
                                            val statusCode: Int?,
                                            val message: String?)

API响应格式::

    {
       "data" : {...}
       "status_code" : 0
       "error_message" : null
    }

为此我们编写客户端如下,

    httpClient.get("splash").body<DataResponseContainer<SplashEntity>>()

现在,我只需要“数据”对象,所以我想这样写,

    httpClient.get("splash").body<SplashEntity>()
    httpClient.get("login").body<LoginEntity>()

另外,我尝试编写自定义插件,但我不知道该怎么做,

  val DataTransformationPlugin = 
  createClientPlugin("DataTransformationPlugin") {

transformResponseBody { response, content, requestedType ->

    val mapper = ObjectMapper()
    if(response.status.isSuccess()) {
        try {
            val user: ResponseWrapper<*> = mapper.readValue(response.bodyAsText(), ResponseWrapper::class.java)
            //Now i want to deserialize it to get only "data" in called body
        } catch (e: Exception) {
            content
        }

    } else
        content
}

}

响应模式:

data class SplashEntity(val lang: String, val type: String)
data class LoginEntity(val id: Int, val role: String)

飞溅响应:

{
  data: {
    "lang": "en",
    "type": "owner",
    
  },
  "statusCode": 200,
  "message": ""
}

登录响应:

{
  data: {
    "id": 1244,
    "role": "admin",
    
  },
  "statusCode": 200,
  "message": ""
}
jackson json-deserialization kotlin-multiplatform ktor ktor-client
1个回答
0
投票

您是否正在寻找

ContentNegotiation
课程?看看https://ktor.io/docs/serialization.html#implement_custom_serializer,只需要实现两个函数即可。

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