Created
August 21, 2017 13:30
-
-
Save stefanmedack/005971818edbf56e059f121cd4908c76 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
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