我正在尝试在Kotlin中编写一个Moshi适配器,它将根据整数值创建枚举,如果遇到不支持的值,也会默认为特定的枚举值。
永远不会调用我的适配器,这会导致默认的枚举适配器因包含的堆栈跟踪而失败。
跟踪代码显示@ToJson
注释以某种方式不存在,因此适配器isn't added when it should be。
声明适配器
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)
...