改造多个响应类型数组或对象

时间:2018-08-31 13:41:20

标签: kotlin retrofit moshi

我想解析一个API的多种响应类型。该API可以提供用户对象数组或完全不同类型的单个Json对象。我将moshi用​​于经过改造的转换器工厂。通过使用moshi我在API给JsonArray作为响应时获得LinkedHashMapTree的ArrayList,而在其他情况下则得到LinkedHashMapTree。我想将ArrayList中的LinkedHashMapTree对象转换为用户类型ArrayList,否则将LinkedHashMapTree转换为相应的对象。

改装设置:

@Provides
@Singleton
fun provideMoshi(): Moshi {
    return Moshi.Builder()
            .build()
}

@Provides
@Singleton
fun provideRetrofit(client: OkHttpClient, moshi: Moshi, apiConfig: ApiConfig): Retrofit {
    return Retrofit.Builder()
            .baseUrl(apiConfig.baseUrl)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()
}

Api:

@Headers("No-Authorization: true")
@POST("mobileotp/confirmOtp")
fun confirmOTP(@Body confirmOTPBody: ConfirmOTPBody): Single<Any>

用法:

mobileOtp.value?.let {
        val request = frappRepository.confirmOtp(ConfirmOTPBody(it.mobile, otp))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe {}
                .subscribe({ data, error ->
                    data?.let {

                        Log.i("CHECKING TYPE", it.javaClass.name)
                        val arrayType = data as? ArrayList<Any>


                        Log.i("CHECKING INTERNAL TYPE", arrayType!![0].javaClass.name)
//                            if (it.("[")) {
//                                val adapter = moshi.adapter<Array<User>?>(Array<User?>::class.java)
//                                usersOrUser.value = adapter.fromJson(it)
//                            } else {
//                                val adapter = moshi.adapter<UserTokens?>(UserTokens::class.java)
//                                usersOrUser.value = adapter.fromJson(it)
//                            }
                        }
                    error?.let {

                    }
                })
        compositeDisposable?.add(request)
    }

0 个答案:

没有答案