未调用Kotlin-Moshi适配器
我正在尝试在Kotlin中编写一个Moshi适配器,它将基于整数值创建枚举,如果遇到不支持的值,它还将默认为特定的枚举值 我的适配器从未被调用,这会导致默认枚举适配器因包含stacktrace而失败 跟踪代码表明未调用Kotlin-Moshi适配器,kotlin,retrofit2,moshi,Kotlin,Retrofit2,Moshi,我正在尝试在Kotlin中编写一个Moshi适配器,它将基于整数值创建枚举,如果遇到不支持的值,它还将默认为特定的枚举值 我的适配器从未被调用,这会导致默认枚举适配器因包含stacktrace而失败 跟踪代码表明@ToJson注释不知何故不存在,因此适配器也不存在 声明适配器 enum class Status { IDLE, IN_PROGRESS, FAILED, SUCCESS, UNKNOWN; companion object {
@ToJson
注释不知何故不存在,因此适配器也不存在
声明适配器
enum class Status {
IDLE,
IN_PROGRESS,
FAILED,
SUCCESS,
UNKNOWN;
companion object {
private val map = Status.values().associateBy(Status::ordinal);
fun fromInt(type: Int?): Status {
var ret = map[type]
if (ret == null) {
ret = UNKNOWN
}
return ret
}
}
class Adapter {
@ToJson
fun toJson(status: Status): Int {
return status.ordinal
}
@FromJson
fun fromJson(value: Int): Status {
return fromInt(value)
}
}
}
摩希大厦
@Provides
@Singleton
fun provideMoshi(): Moshi {
return Moshi.Builder()
.add(Status.Adapter())
.add(KotlinJsonAdapterFactory())
.build()
}
依赖关系
implementation 'com.squareup.moshi:moshi:1.6.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.6.0'
堆栈跟踪
05-29 18:57:56.603 24560-24560/com.example.app E/MyActivity: com.squareup.moshi.JsonDataException: Expected one of [IDLE, IN_PROGRESS, FAILED, SUCCESS, UNKNOWN] but was 2 at path $[0].status
at com.squareup.moshi.StandardJsonAdapters$EnumJsonAdapter.fromJson(StandardJsonAdapters.java:297)
at com.squareup.moshi.StandardJsonAdapters$EnumJsonAdapter.fromJson(StandardJsonAdapters.java:266)
at com.squareup.moshi.JsonAdapter$2.fromJson(JsonAdapter.java:137)
at com.squareup.moshi.ClassJsonAdapter$FieldBinding.read(ClassJsonAdapter.java:196)
at com.squareup.moshi.ClassJsonAdapter.fromJson(ClassJsonAdapter.java:158)
at com.squareup.moshi.JsonAdapter$2.fromJson(JsonAdapter.java:137)
at com.squareup.moshi.CollectionJsonAdapter.fromJson(CollectionJsonAdapter.java:76)
at com.squareup.moshi.CollectionJsonAdapter$2.fromJson(CollectionJsonAdapter.java:53)
at com.squareup.moshi.JsonAdapter$2.fromJson(JsonAdapter.java:137)
at retrofit2.converter.moshi.MoshiResponseBodyConverter.convert(MoshiResponseBodyConverter.java:45)
at retrofit2.converter.moshi.MoshiResponseBodyConverter.convert(MoshiResponseBodyConverter.java:27)
...
我无法复制这个。你有没有告诉你的改装实例你的Moshi实例?非常感谢杰西。你的直觉是正确的。我未能将我的
Moshi
实例传递到我的MoshiConverterFactory
。谢谢你的帮助!