Skip to content

Instantly share code, notes, and snippets.

@stefanmedack
Created August 21, 2017 13:30
Show Gist options
  • Save stefanmedack/005971818edbf56e059f121cd4908c76 to your computer and use it in GitHub Desktop.
Save stefanmedack/005971818edbf56e059f121cd4908c76 to your computer and use it in GitHub Desktop.
package com.ajnsnewmedia.kitchenstories.moshi.adapter
import com.squareup.moshi.*
import java.io.IOException
import java.lang.reflect.Type
class FilterNullValuesFromListAdapter<T : Any> private constructor(private val delegate: JsonAdapter<List<T?>>) : JsonAdapter<List<T>>() {
@Throws(IOException::class)
override fun fromJson(reader: JsonReader): List<T> {
return delegate.fromJsonValue(reader.readJsonValue())?.filterNotNull() ?: listOf()
}
@Throws(IOException::class)
override fun toJson(writer: JsonWriter, value: List<T>?) {
delegate.toJson(writer, value)
}
companion object {
@JvmStatic fun <T : Any> newFactory(type: Class<T>): JsonAdapter.Factory {
return object : JsonAdapter.Factory {
override fun create(requestedType: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
val listType = Types.newParameterizedType(List::class.java, type)
if (listType != requestedType) {
return null
}
val delegate = moshi.nextAdapter<List<T?>>(this, listType, annotations)
return FilterNullValuesFromListAdapter(delegate)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment