Skip to content

Instantly share code, notes, and snippets.

@daneko
Created December 2, 2019 07:58
Show Gist options
  • Save daneko/c8a9d37d3252bf77f3a53fccd150d5b9 to your computer and use it in GitHub Desktop.
Save daneko/c8a9d37d3252bf77f3a53fccd150d5b9 to your computer and use it in GitHub Desktop.
import arrow.core.*
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
class OptionJsonAdapterFactory : JsonAdapter.Factory {
override fun create(type: Type, annotations: MutableSet<out kotlin.Annotation>, moshi: Moshi): JsonAdapter<*>? {
return if (type is ParameterizedType && Option::class.java == type.rawType) {
OptionAdapter(moshi, type.actualTypeArguments[0])
} else null
}
private class OptionAdapter(private val moshi: Moshi, private val type: Type) : JsonAdapter<Option<*>>() {
private var adapter: JsonAdapter<Any>? = null
override fun toJson(writer: JsonWriter, value: Option<*>?) {
when (value) {
is Some -> {
if (adapter == null) {
adapter = moshi.adapter(type)
}
adapter!!.toJson(writer, value.t)
}
is None -> writer.nullValue()
}
}
override fun fromJson(reader: JsonReader): Option<*> {
if (JsonReader.Token.NULL === reader.peek()) {
reader.skipValue()
return none<Nothing>()
}
if (adapter == null) {
adapter = moshi.adapter(type)
}
return adapter!!.fromJson(reader).toOption()
}
}
}
Moshi.Builder()
.add(OptionJsonAdapterFactory())
.add(KotlinJsonAdapterFactory())
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment