在Android中使用Retrofit2和Kotlin进行REST API请求时,有时候可能会遇到请求的响应格式与模型不一致的问题。以下是一种解决方法:
data class UserResponse(
val id: Int,
val name: String,
val email: String
)
interface ApiService {
@GET("user/{id}")
suspend fun getUser(@Path("id") id: Int): UserResponse
}
val apiService = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
try {
val userResponse = apiService.getUser(1)
// 处理响应
// ...
} catch (e: Exception) {
// 处理异常
// ...
}
@SerializedName
注解来映射它们:data class UserResponse(
val id: Int,
@SerializedName("user_name") val name: String,
val email: String
)
这样,Retrofit就能正确地将API响应映射到数据类中。
通过以上步骤,您可以解决Android中使用Retrofit2和Kotlin进行REST API请求时,请求的响应格式与模型不一致的问题。
上一篇:Android - retrofit - 如何发送包含多个值的字符串列表
下一篇:Android - Retrofit: java.security.cert.CertPathValidatorException: 未找到证书路径的信任锚