Skip to content

Instantly share code, notes, and snippets.

@naturalwarren
Created May 13, 2018 19:48
Show Gist options
  • Save naturalwarren/f54d8dd908522b01db4ed16bb115ff91 to your computer and use it in GitHub Desktop.
Save naturalwarren/f54d8dd908522b01db4ed16bb115ff91 to your computer and use it in GitHub Desktop.
/**
* Complements @Enveloped by performing custom deserialization
* for a response that is wrapped in a JSON Object.
*/
internal class EnvelopeFactory : JsonAdapter.Factory {
companion object {
val INSTANCE = EnvelopeFactory()
}
override fun create(
type: Type,
annotations: MutableSet<out Annotation>,
moshi: Moshi): JsonAdapter<*>? {
val delegateAnnotations = Types.nextAnnotations(
annotations,
Enveloped::class.java) ?: return null
val delegate = moshi.nextAdapter<Any>(
this,
type,
delegateAnnotations)
return EnvelopeJsonAdapter(delegate)
}
private class EnvelopeJsonAdapter(val delegate: JsonAdapter<*>) : JsonAdapter<Any>() {
override fun fromJson(reader: JsonReader): Any? {
reader.beginObject()
reader.nextName()
val envelope = delegate.fromJson(reader)
reader.endObject()
return envelope
}
override fun toJson(writer: JsonWriter?, value: Any?)
= throw UnsupportedOperationException(
"@Enveloped is only used to deserialize objects.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment