我正在使用的API根据对象是否填充而具有两种不同类型的JSON。如果已填充,则为JSON对象,否则为JSON数组,我将如何在Retrofit中进行处理?
空
"errors": []
不为空
"errors": {
"licence": [
"You have too many points on your licence"
],
"general": [
"An error occurred during your verification, please contact support"
]
}
我该如何使用Retrofit进行处理,以便在处理响应时不会导致错误?
答案 0 :(得分:0)
这与改造无关,但与您使用的JSON Deserializer无关。 我猜您正在使用GSON适配器进行翻新。然后,您别无选择,只能为响应编写自定义反序列化器。
让我给你看一个例子(在Kotlin中):
sealed class ErrorResponse {
object Empty : ErrorResponse()
data class ApiError(val licence: List<String>, val general: List<String>) : ErrorResponse()
}
//make sure you call function in the retrofit interface is set to the correct type
@GET("errors")
fun getErrorResponse() : Call<ErrorResponse>
class ErrorResponseDeserializer : JsonDeserializer<ErrorResponse> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ErrorResponse {
return when(json) {
is JsonObject -> {
context.deserialize<ErrorResponse.ApiError>(json, ErrorResponse.ApiError::class.java)
}
else -> ErrorResponse.Empty
}
}
}
//create gson instance and register the deserializer
val gson = GsonBuilder()
.registerTypeAdapter(ErrorResponse::class.java, ErrorResponseDeserializer())
.create()
//use own gson instance for the gson converter factory
Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
...
//or use rxjava / coroutines etc for the response handling
override fun onResponse(call: Call<ErrorResponse>, response: Response<ErrorResponse>) {
val body = response.body()
when(body) {
is ErrorResponse.Empty -> {
//TODO handle empty array state
}
is ErrorResponse.ApiError -> {
//TODO handle api errors or whatever you want
val general = body.general //smart cast kotlin <3
}
}
}