Last active
January 31, 2021 02:30
-
-
Save dlew/9eed3d854b85aa6b628e90532add6e41 to your computer and use it in GitHub Desktop.
Gson -> Moshi name snafu detector
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
@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