Last active
February 16, 2019 01:05
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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