如何使用 Moshi 将 json 中的 int 列表转换为枚举的 list/array?

How to convert list of int in json to list/array of enums using Moshi?

我正在从 API 中获取一个整数列表(实际上是枚举)。当我尝试解析它时,我得到:Unable to create converter for java.util.List<MyEnum>

我的适配器目前看起来像这样:

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class MyEnumListAnnotation

class MyEnumListAdapter {
    @ToJson
    fun toJson(@MyEnumListAnnotation myEnumList: List<MyEnum>): List<Int> {
        return myEnumList.map { it.type }
    }

    @FromJson
    @MyEnumListAnnotation
    fun fromJson(typeList: List<Int>): List<MyEnum> {
        return typeList.map { MyEnum.from(it) }
    }
}

我像这样将其添加到网络客户端:

Moshi.Builder()
                    .add([A lot of other adapters])
                    .add(MyEnumListAdapter())

我正在使用这样的注释(在我要解析的对象中):

data class InfoObject(
        val id: String,
        val name: String,
        val email: String,
        val phone: String,

        @MyEnumListAnnotation
        val myEnums: List<MyEnum>
)

我如何编写我的适配器才能正常工作?感谢所有帮助。 :)

如果您使用 Moshi 的 codegen(您应该这样做),您只需为 MyEnum 本身编写适配器。

class MyEnumAdapter {
    @ToJson
    fun toJson(enum: MyEnum): Int {
        return enum.type
    }

    @FromJson
    fun fromJson(type: Int): MyEnum {
        return MyEnum.from(it)
    }
}

按照您在问题中所做的方式将适配器连接到您的 Moshi 构建器。然后,更新您的 InfoObject:

@JsonClass(generateAdapter = true)
data class InfoObject(
        @Json(name = "id") val id: String,
        @Json(name = "name") val name: String,
        @Json(name = "email") val email: String,
        @Json(name = "phone") val phone: String,
        @Json(name = "myEnums") val myEnums: List<MyEnum>
)

@JsonClass(generateAdapter = true) 将确保库将为您的 InfoObject 提供一个适配器 auto-create,包括 List<MyEnum> 的一个适配器(您尝试自己创建的适配器),因此您不必自己创建这些适配器。 @Json(name="...")只是约定,可以省略。

要集成codegen,只需添加依赖项:

kapt("com.squareup.moshi:moshi-kotlin-codegen:1.9.3")

有关详细信息,请参阅 https://github.com/square/moshi