问题描述
我在这里可能错得很厉害,这是我第一次将自定义适配器与moshi一起使用。
基本上,它的作用是我没有为Pair注册适配器,但我(至少据我所知)注册了。
这是我的适配器类:
internal class PairAdapter(
private val firstAdapter: JsonAdapter<Any>,private val secondAdapter: JsonAdapter<Any>,private val listadapter: JsonAdapter<List<String>>
): JsonAdapter<Pair<Any,Any>>() {
override fun toJson(writer: JsonWriter,value: Pair<Any,Any>?) {
value ?: throw NullPointerException("value == null")
writer.beginArray()
firstAdapter.toJson(writer,value.first)
secondAdapter.toJson(writer,value.second)
writer.endarray()
}
override fun fromJson(reader: JsonReader): Pair<Any,Any>? {
val list = listadapter.fromJson(reader) ?: return null
require(list.size == 2) { "Pair with more or less than two elements: $list" }
val first = firstAdapter.fromJsonValue(list[0])
?: throw IllegalStateException("Pair without first")
val second = secondAdapter.fromJsonValue(list[1])
?: throw IllegalStateException("Pair without second")
return first to second
}
}
class PairAdapterFactory: JsonAdapter.Factory {
override fun create(
type: Type,annotations: MutableSet<out Annotation>,moshi: moshi,): JsonAdapter<*>? {
if (type !is ParameterizedType || Pair::class.java != type.rawType) return null
val listType = Types.newParameterizedType(List::class.java,String::class.java)
val listadapter = moshi.adapter<List<String>>(listType)
return PairAdapter(
moshi.adapter(type.actualTypeArguments[0]),moshi.adapter(type.actualTypeArguments[1]),listadapter
)
}
}
这是我称之为的转换器之一:
@TypeConverter
fun fromOffspringListToJson(offspringList: List<Pair<Set<Trait>,Int>>): String {
val moshi = moshi.Builder()
.add(PairAdapterFactory())
.add(KotlinjsonAdapterFactory())
.build()
val offspringListWithStringFirsts = offspringList.map {
Pair(
fromTraitSetToJson(it.first),it.second
)
}
val mapType = Types.newParameterizedType(
List::class.java,Pair::class.java,String::class.javaObjectType,Int::class.javaObjectType
)
val jsonAdapter: JsonAdapter<List<Pair<String,Int>>> = moshi.adapter(mapType)
return jsonAdapter.toJson(offspringListWithStringFirsts)
}
我想念什么? 预先谢谢你。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)