【问题标题】:Moshi cannot find my custom adapter written in Kotlin for a parameterized typeMoshi 找不到我用 Kotlin 为参数化类型编写的自定义适配器
【发布时间】:2019-01-04 00:45:37
【问题描述】:

我有一个用于 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&lt;okio.ByteString&gt; annotated [@HexString()]

为什么 Moshi 没有找到我为 @HexString List&lt;ByteString&gt; 注册的适配器?

【问题讨论】:

    标签: java json kotlin moshi


    【解决方案1】:

    toJson 函数在参数上需要@JvmSuppressWildcards

    @ToJson fun toJson(@HexString byteStrings: List<@JvmSuppressWildcards ByteString>): List<String> {
      return byteStrings.map { it.hex() }
    }
    

    没有它,Moshi 看到List&lt;? extends ByteString&gt; 并且无法匹配类型以找到适配器。

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2017-03-09
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2017-02-08
      • 2018-02-21
      • 1970-01-01
      相关资源
      最近更新 更多