Skip to content

Instantly share code, notes, and snippets.

@Fi5t
Last active January 11, 2019 18:35
Show Gist options
  • Save Fi5t/3865c198a699e565b434413885ef3579 to your computer and use it in GitHub Desktop.
Save Fi5t/3865c198a699e565b434413885ef3579 to your computer and use it in GitHub Desktop.
val moshi = Moshi.Builder()
.add(SkipBadListObjectsAdapterFactory())
.build()
class SkipBadListObjectsAdapterFactory : JsonAdapter.Factory {
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<*>? {
return if (annotations.isEmpty() && Types.getRawType(type) == List::class.java) {
val elementType = Types.collectionElementType(type, List::class.java)
val elementAdapter = moshi.adapter<Any>(elementType)
SkipBadListObjectsAdapter(elementAdapter)
} else {
null
}
}
private class SkipBadListObjectsAdapter<T : Any>(private val elementAdapter: JsonAdapter<T>) :
JsonAdapter<List<T>>() {
override fun fromJson(reader: JsonReader): List<T>? {
val goodObjectsList = mutableListOf<T>()
reader.beginArray()
while (reader.hasNext()) {
try {
elementAdapter.fromJson(reader)?.let(goodObjectsList::add)
} catch (e: JsonDataException) {
// Skip bad element ;)
}
}
reader.endArray()
return goodObjectsList
}
override fun toJson(writer: JsonWriter, value: List<T>?) {
throw UnsupportedOperationException("SkipBadListObjectsAdapter is only used to deserialize objects")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment