我有一个数据类User:
@JsonClass(generateAdapter = true)
data class User(val accountName: String,
val gender: Gender,
val title: Title? = null)
)
其中性别和头衔必须仅具有以枚举形式编写的一些值:
enum class Gender(val value: Int) {
MALE(0), FEMALE(1), UNSPECIFIED(-1)
}
enum class Title(val value: String) {
MRS("Mrs"), MS("Ms")
}
我将EnumJsonAdapter
添加到了moshi builder中,但是它不起作用。
fun fromJson(json: String): User? {
val builder = Moshi.Builder()
.add(Title::class.java, EnumJsonAdapter.create<Title>(Title::class.java).withUnknownFallback(null))
.add(Gender::class.java, EnumJsonAdapter.create<Gender>(Gender::class.java).withUnknownFallback(Gender.UNSPECIFIED))
.build()
val jsonAdapter = builder.adapter(User::class.java)
return jsonAdapter.fromJson(json)
}
fun toJson(obj: User): String {
val builder = Moshi.Builder()
.add(Title::class.java, EnumJsonAdapter.create<Title>(Title::class.java).withUnknownFallback(null))
.add(Gender::class.java, EnumJsonAdapter.create<Gender>(Gender::class.java).withUnknownFallback(Gender.UNSPECIFIED))
.build()
val jsonAdapter = builder.adapter(User::class.java).serializeNulls()
return jsonAdapter.toJson(obj)
}
我收到title =“ Mr”,它被解析为null。关于性别,我得到了这个例外:
com.squareup.moshi.JsonDataException: Expected a string but was NUMBER at path $.data.gender
at com.squareup.moshi.adapters.EnumJsonAdapter.fromJson(EnumJsonAdapter.java:93)
EnumJsonAdapter
是我做错了什么吗?所以我看到了,它不能用于int,但是为什么它对于标题为String的标题不能正常工作?
如果我对这些枚举使用自定义适配器,则一切正常。