【发布时间】:2019-04-03 05:54:22
【问题描述】:
我的JSON 服务器响应通常是这样的[{}](对象数组),除了他们设置错误以返回对象{} 所以当我打电话时当然如果响应有问题并且它返回一个对象我得到以下错误:
Expected BEGIN_ARRAY but was BEGIN_OBJECT
在我的代码中,因为我期待一个 ArrayList 并获取一个对象(但我不确定如何处理这个问题?当我得到对象时,这意味着 API 调用存在问题,我需要处理对象中响应的内容。
来自 API 的示例错误响应:
{
"StatusCode": -7,
"StatusMessage": "Invalid",
"Details": ""
}
APIService接口如下:
interface MyAPIService {
@GET("RequestByToken")
fun getCurrentRequestAsync(
@Query("token") token: String
): Deferred<List<CurrentResponse>>
companion object {
operator fun invoke(
connectivityInterceptor: ConnectivityInterceptor
): MyAPIService {
val requestInterceptor = Interceptor { chain ->
//Creates a new URL adding in the CONST'S
val url = chain.request()
.url()
.newBuilder()
.addQueryParameter("format", FORMAT)
.build()
//Creates new Request with the new URL
val request = chain.request()
.newBuilder()
.url(url.toString())
.build()
println(request)
return@Interceptor chain.proceed(request)
}
//Intercepts each http call and adds the url above automatically
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(requestInterceptor)
.addInterceptor(connectivityInterceptor)
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_URL)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(MyAPIService::class.java)
}
}
}
【问题讨论】:
-
尝试
Deferred<Any>而不是Deferred<List<CurrentResponse>>它将接受所有模型响应检查 if(response.body is List){//这意味着它是你的数组} else { //这是错误的回应 -
返回 Any 时遇到的问题是,当我需要使用 List
并将其设置为 List 时,它抱怨它无法从 LinkedTreeMap 转换它? -
onFailure 方法中返回此错误
标签: android json api kotlin retrofit2