Created
February 4, 2022 03:41
-
-
Save sushant-droid/a3b673f513717b43550950cbcc1307cb to your computer and use it in GitHub Desktop.
Gson type adapter for post processing
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
internal class RequiredFieldsTypeAdpaterFactory : TypeAdapterFactory { | |
override fun <T : Any> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { | |
val delegate = gson.getDelegateAdapter(this, type) | |
val objectValidator = type.rawType.getAnnotation(EmptyObjectValidator::class.java) ?: return null | |
return object: TypeAdapter<T>() { | |
override fun write(out: JsonWriter?, value: T) { | |
delegate.write(out, value) | |
} | |
override fun read(`in`: JsonReader?): T { | |
val result = delegate.read(`in`) | |
val postDeserializer: JsonPostDeserializer<*> = objectValidator.deserializer.javaObjectType.newInstance() | |
postDeserializer.postDeserialize(result) | |
return result | |
} | |
} | |
} | |
} | |
@Retention(AnnotationRetention.RUNTIME) | |
@Target(AnnotationTarget.CLASS) | |
annotation class EmptyObjectValidator(val deserializer: KClass<out JsonPostDeserializer<*>>) | |
@EmptyObjectValidator(FluffValidator::class) | |
data class Fluff(val blah: String = "") | |
class FluffValidator: JsonPostDeserializer<Fluff> { | |
override fun postDeserialize(type: Fluff) { | |
TODO("Not yet implemented") | |
} | |
} | |
interface JsonPostDeserializer<T> { | |
fun postDeserialize(type: T) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment