Created
December 2, 2019 07:58
-
-
Save daneko/c8a9d37d3252bf77f3a53fccd150d5b9 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
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