Moshi 找不到我用 Kotlin 为参数化类型编写的自定义适配器

Moshi cannot find my custom adapter written in Kotlin for a parameterized type

我有一个用于 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> 并且无法匹配类型以找到适配器。