Created
March 10, 2023 09:39
-
-
Save gaara87/158fb0dd5d503d7ac69c1d236a3f554b to your computer and use it in GitHub Desktop.
Moshi json adapter factory for KotlinX's ImmutableList
This file contains hidden or 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
import com.squareup.moshi.JsonAdapter | |
import com.squareup.moshi.JsonReader | |
import com.squareup.moshi.JsonWriter | |
import com.squareup.moshi.Moshi | |
import com.squareup.moshi.rawType | |
import kotlinx.collections.immutable.ImmutableList | |
import kotlinx.collections.immutable.persistentListOf | |
import java.lang.reflect.ParameterizedType | |
import java.lang.reflect.Type | |
object ImmutableListJsonAdapterFactory : JsonAdapter.Factory { | |
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<*>? { | |
if (!ImmutableList::class.java.isAssignableFrom(type.rawType) || | |
type !is ParameterizedType | |
) { | |
return null | |
} | |
val elementType = type.actualTypeArguments[0] | |
val elementAdapter = moshi.adapter(elementType.rawType) | |
return Adapter(elementAdapter) | |
} | |
private class Adapter<E>(private val elementAdapter: JsonAdapter<E>) : NullSafeJsonAdapter<ImmutableList<E>>() { | |
override fun readFrom(reader: JsonReader): ImmutableList<E> { | |
val listBuilder = persistentListOf<E>().builder() | |
reader.beginArray() | |
while (reader.hasNext()) { | |
listBuilder.add(elementAdapter.fromJson(reader)!!) | |
} | |
reader.endArray() | |
return listBuilder.build() | |
} | |
override fun writeTo(writer: JsonWriter, value: ImmutableList<E>) { | |
writer.beginArray() | |
for (element: E in value) { | |
elementAdapter.toJson(writer, element) | |
} | |
writer.endArray() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment