Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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) != {
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(, 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
You can’t perform that action at this time.