Moshi找不到我用Kotlin编写的自定义适配器作为参数化类型 [英] Moshi cannot find my custom adapter written in Kotlin for a parameterized type

查看:80
本文介绍了Moshi找不到我用Kotlin编写的自定义适配器作为参数化类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对Moshi的自定义JSON适配器,以获取字节串列表,如下所示.

I have a custom JSON adapter for Moshi for a list of byte strings like the following.

@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()].

Even though I have registered it properly in main here, running this program will fail with java.lang.IllegalArgumentException: No @ToJson adapter for java.util.List<okio.ByteString> annotated [@HexString()].

为什么Moshi找不到我的@HexString List<ByteString>注册适配器?

Why is Moshi not finding my registered adapter for @HexString List<ByteString>?

推荐答案

toJson函数需要 @JvmSuppressWildcards .

The toJson function needs @JvmSuppressWildcards on the parameter.

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

没有它,Moshi将看到List<? extends ByteString>,并且无法匹配类型以找到适配器.

Without it, Moshi sees List<? extends ByteString> and cannot match the types to find the adapter.

这篇关于Moshi找不到我用Kotlin编写的自定义适配器作为参数化类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆