Created
May 13, 2018 19:48
-
-
Save naturalwarren/f54d8dd908522b01db4ed16bb115ff91 to your computer and use it in GitHub Desktop.
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
/** | |
* 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