【发布时间】:2022-07-28 20:55:16
【问题描述】:
我收到了来自 BE 的回复,回复是 base64 编码的图像。响应如下所示:
{"image":"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/ ...}(此处完整回复:https://pastebin.com/ViFTAhRw)
看起来像一个名为image 的属性,后跟一个字符串。所以我创建了我的模型类:
@JsonClass(generateAdapter = true)
data class ApiBase64Image(
@field:Json(name = "image") val imageString: String?
) {
fun toDomain(): Base64Image {
return Base64Image(imageString.orEmpty())
}
}
最后,我的 DI 对象:
@Module
@InstallIn(SingletonComponent::class)
object ApiModule {
@Provides
@Singleton
fun provideApi(builder: Retrofit.Builder): MyApi {
return builder
.build()
.create(MyApi::class.java)
}
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit.Builder {
return Retrofit.Builder()
.baseUrl(ApiConstants.BASE_ENDPOINT)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create())
}
@Provides
fun provideOkHttpClient(
authenticationInterceptor: AuthenticationInterceptor
): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(authenticationInterceptor)
.build()
}
}
但是,此代码不起作用,因为我收到错误:
Unable to create converter for class ... .ApiBase64Image
Failed to find the generated JsonAdapter class for class ... .ApiBase64Image
我不确定是什么给 Moshi 带来了问题。是数据类序列化吗?还是我的 DI 设置?还是完全不同的东西?
【问题讨论】:
-
你的项目中添加了moshi codegen插件和依赖了吗?即使您可以访问注解,但没有 codegen 插件和依赖项,也不会处理和生成带有注解的适配器。
-
@VictorFerrucy 我做了,特别是我有
implementation "com.squareup.moshi:moshi-kotlin:1.13.0"和implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
标签: android kotlin retrofit dagger-hilt moshi