/api/type
第一个端点返回JSON,这很好。但是,第二个端点不会返回JSON,而是返回对象的数组。
看起来像这样的响应:
api/type
其他终点返回“常见”json.
我正在使用改造,Okhttp和匕首。
改造模块的设置如下:[["Model",123],["ModelB",456],["ModelC",789]]
this呼叫时工作正常@InstallIn(SingletonComponent::class)
@Module
class APIModule {
@Singleton
@Provides
@Named("default")
fun provideDefaultOkHttpClient(): OkHttpClient =
OkHttpClient
.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
@Singleton
@Provides
fun provideRetrofit(
@Named("default") okHttpClient: OkHttpClient
): Retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://test.com")
.client(okHttpClient)
.build()
}
api/products
:
api/type
API服务如下:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]
我知道问题是,对于一个端点而言,响应是json,在另一个情况下,它是一个类似的数组:interface Service {
@GET("api/type")
suspend fun getType(): Array<Pair<String, Int>>
任何想法如何使它起作用? 还有什么可以让我同时支持JSON和数组?
创建了一个在数组/列表中使用的类:
[["Model",123],["ModelB",456],["ModelC",789]]
写入自定义求职者:
addConverterFactory
@JsonAdapter(DataDeserializer::class)
internal data class Data(
val string: String,
val value: Int
)
确保指定
internal class DataDeserializer : JsonDeserializer<Data> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): Data? {
if (json?.isJsonArray != true) {
return null
}
val jsonArray = json.asJsonArray
val string = jsonArray[0].asString
val value = jsonArray[1].asInt
return Data(string, value)
}
}
internal interface Service {
@GET("api")
suspend fun getData(): ArrayList<Data>
}
,您可以通过添加拦截器来替换服务器的测试数据:
addConverterFactory(GsonConverterFactory.create())