Last active
January 11, 2019 18:35
-
-
Save Fi5t/3865c198a699e565b434413885ef3579 to your computer and use it in GitHub Desktop.
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
val moshi = Moshi.Builder() | |
.add(SkipBadListObjectsAdapterFactory()) | |
.build() |
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 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