我有一个用于 Moshi 的自定义 JSON 适配器,用于字节字符串列表,如下所示。
@Retention(RUNTIME)
@JsonQualifier
annotation class HexString
object ByteStringListAdapter {
@ToJson fun toJson(@HexString byteStrings: List<@JvmSuppressWildcards ByteString>): List<String> {
return byteStrings.map { it.hex() }
}
@FromJson @HexString fun fromJson(json: List<String>): List<@JvmSuppressWildcards ByteString> {
return json.map { ByteString.decodeHex(it) }
}
}
fun main(args: Array<String>) {
val moshi = Moshi.Builder()
.add(ByteStringListAdapter)
.build()
val byteStringListAdapter = moshi.adapter<List<ByteString>>(
Types.newParameterizedType(List::class.java, ByteString::class.java), HexString::class.java)
}
即使我已经在 main
中正确注册了它在这里,运行该程序将失败并显示 java.lang.IllegalArgumentException: No @ToJson adapter for java.util.List<okio.ByteString> annotated [@HexString()]
.
为什么 Moshi 找不到我为 @HexString List<ByteString>
注册的适配器?
最佳答案
toJson
功能需求 @JvmSuppressWildcards
在参数上。
@ToJson fun toJson(@HexString byteStrings: List<@JvmSuppressWildcards ByteString>): List<String> {
return byteStrings.map { it.hex() }
}
没有它,Moshi 会看到 List<? extends ByteString>
无法匹配类型以找到适配器。
关于java - Moshi 找不到我用 Kotlin 为参数化类型编写的自定义适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51548692/