平台类java.util.Collections $ SingletonMap(无注释)需要显式的JsonAdapter进行注册

时间:2018-12-02 03:32:32

标签: moshi

如果我正确地收到错误消息,则必须为java.util.Collections$SingletonMap类型创建并传递Moshi一个自定义JsonAdapter。问题在于, SingletonMap 在“收藏夹”中是私有的。

val movies: MutableList<Movie> = Collections.synchronizedList(mutableListOf(
    Movie("Home alone"),
    Movie("Terminator"),
    Movie("Independence day")
))
// and later
get("/movies") {
     call.respond(mapOf("movies" to synchronized(movies) { movies.toList() }))
}

此处mapOf()返回Map<String, List<Movie>>并由java.util.Collections.singletonMap(K key, V value)支持,后者返回 SingletonMap

我尝试实现JsonAdapter for Map。虽然没有帮助

    class MapJsonAdapter(
                private val elementAdapter: JsonAdapter<Any?>
            ) : JsonAdapter<Map<Any, Any?>>() {
            object Factory : JsonAdapter.Factory {
                override fun create(type: Type, annotations: Set<Annotation>,
                                    moshi: Moshi
                ): JsonAdapter<*>? {
                    if (annotations.isNotEmpty()) return null
                    val rawType = Types.getRawType(type)
                    if (rawType != Map::class.java) return null
                    val elementType = (type as ParameterizedType).actualTypeArguments[0]
                    return MapJsonAdapter(moshi.adapter(elementType))
                }
            }

            override fun fromJson(reader: JsonReader): Map<Any, Any?> {
                throw UnsupportedOperationException()
            }

            override fun toJson(writer: JsonWriter, value: Map<Any, Any?>?) {
                checkNotNull(value, { "Adapter doesn't support null. Wrap with nullSafe()." }).apply {
                    writer.beginObject()
                    value.forEach { t, u ->
                        elementAdapter.toJson(writer, t)
                        elementAdapter.toJson(writer, u)
                    }
                    writer.endObject()
                }
            }
        }

    // Usage in ktor
    //...
    install(ContentNegotiation) {
            moshi {
                add(MapJsonAdapter.Factory)
            }
        }

有什么办法可以解决这个问题?

0 个答案:

没有答案
相关问题