Created
July 12, 2022 17:58
-
-
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
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
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