Skip to content

Instantly share code, notes, and snippets.

@90K2
Created July 12, 2022 17:58
Show Gist options
  • Save 90K2/274effa619ea0af4c937e8c217820c3f to your computer and use it in GitHub Desktop.
Save 90K2/274effa619ea0af4c937e8c217820c3f to your computer and use it in GitHub Desktop.
Kotlin extension for serialization data objects with @JsonProperty annotated values instead of field names. Reflextion style
fun Any.forceSerialize(separator: String, sorted: Boolean = false): String {
var fieldNameToAnnotatedNameMap = this.javaClass.declaredFields.map { it.name }.associateWith { fieldName ->
val jsonFieldName =
this::class.primaryConstructor?.parameters?.first { it.name == fieldName }?.annotations?.firstOrNull { it is JsonProperty }
val serializedName = if (jsonFieldName != null) (jsonFieldName as JsonProperty).value else fieldName
serializedName
}
if (sorted)
fieldNameToAnnotatedNameMap = fieldNameToAnnotatedNameMap.toList().sortedBy { (_, value) -> value}.toMap()
return fieldNameToAnnotatedNameMap.entries.joinToString(separator) { e ->
val field = this::class.memberProperties.first { it.name == e.key }
"${e.value}=${field.javaGetter?.invoke(this)}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment