Skip to content

Instantly share code, notes, and snippets.

@edenman
Last active February 16, 2019 01:05
Show Gist options
  • Save edenman/e5efe7859e0f14b3d641704e41fd0318 to your computer and use it in GitHub Desktop.
Save edenman/e5efe7859e0f14b3d641704e41fd0318 to your computer and use it in GitHub Desktop.
Original code by @JakeWharton, ported to Kotlin. Useful if you want to maintain insertion order of a Map before/after Moshi serialization.
class LinkedHashMapAdapterFactory : Factory {
override fun create(type: Type, annotations: MutableSet<out Annotation>,
moshi: Moshi): JsonAdapter<*>? {
if (Types.getRawType(type) != LinkedHashMap::class.java) {
return null
}
if (type !is ParameterizedType) {
throw IllegalStateException("Non-parameterized LinkedHashMap is not supported")
}
val keyType = type.actualTypeArguments[0]
val valType = type.actualTypeArguments[1]
val mapType = Types.newParameterizedType(Map::class.java, keyType, valType)
val mapAdapter = moshi.adapter<Map<Any, Any>>(mapType)
return object : JsonAdapter<LinkedHashMap<Any, Any>>() {
override fun fromJson(reader: JsonReader): LinkedHashMap<Any, Any>? {
return LinkedHashMap(mapAdapter.fromJson(reader))
}
override fun toJson(writer: JsonWriter, value: LinkedHashMap<Any, Any>?) {
mapAdapter.toJson(writer, value)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment