Skip to content

Instantly share code, notes, and snippets.

@dlew
Last active January 31, 2021 02:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlew/9eed3d854b85aa6b628e90532add6e41 to your computer and use it in GitHub Desktop.
Save dlew/9eed3d854b85aa6b628e90532add6e41 to your computer and use it in GitHub Desktop.
Gson -> Moshi name snafu detector
@Test
fun verifySerializedNameMatchesJsonName() {
// Reflections library
Reflections("com.foobar").getTypesAnnotatedWith(JsonClass::class.java)
.flatMap { clz ->
// FieldUtils is in Apache Commons
FieldUtils.getAllFieldsList(clz).filter { !Modifier.isStatic(it.modifiers) }
}
.forEach { field ->
val serializedNameAnnotation = field.declaredAnnotations.find { it is SerializedName } as? SerializedName
val jsonAnnotation = field.declaredAnnotations.find { it is Json } as? Json
if (serializedNameAnnotation != null) {
val serializedName = serializedNameAnnotation.value
val jsonName = jsonAnnotation?.name ?: field.name // The field's name is the implicit name in Moshi
if (serializedName != jsonName) {
if (jsonAnnotation == null) {
fail("$field is annotated with a custom @SerializedName but not @Json")
}
else {
fail("$field @SerializedName and @Json have different names")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment