【问题标题】:Failed to generate the Json adapter with Moshi使用 Moshi 生成 Json 适配器失败
【发布时间】: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


【解决方案1】:

@JsonClass(generateAdapter = true)

这是Codegen使用的,所以你需要添加那个依赖:

plugins {
  id("com.google.devtools.ksp").version("1.6.10-1.0.4") // Or latest version of KSP
}

dependencies {
  ksp("com.squareup.moshi:moshi-kotlin-codegen:1.13.0")
}

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 2017-03-09
    • 2021-04-24
    • 2018-02-21
    • 2019-11-23
    • 1970-01-01
    • 2022-08-03
    • 2018-06-17
    相关资源
    最近更新 更多