Skip to content

Instantly share code, notes, and snippets.

@Benjiko99
Created December 6, 2019 09:59
Show Gist options
  • Save Benjiko99/334d725943b8d7dbd9061a231d0d4f42 to your computer and use it in GitHub Desktop.
Save Benjiko99/334d725943b8d7dbd9061a231d0d4f42 to your computer and use it in GitHub Desktop.
Moshi Adapter. Fields annotated with @JsonNullable will be serialized as `null` instead of being ignored.
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class JsonNullable
/**
* Fields annotated with @JsonNullable will be serialized as `null` instead of being ignored.
*/
class JsonNullableAdapter : JsonAdapter.Factory {
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<Any>? {
val nextAnnotations = nextAnnotations(annotations, JsonNullable::class.java) ?: return null
return moshi.nextAdapter<Any>(this, type, nextAnnotations).serializeNulls()
}
}
@Benjiko99
Copy link
Author

Usage example:

data class MyRequest(
    val id: Int,
    @JsonNullable val title: String?
)

@Benjiko99
Copy link
Author

Setup:

val moshi = Moshi.Builder()
    .add(JsonNullableAdapter())
    .build()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment