Created
August 10, 2022 13:52
-
-
Save 90K2/fbeb8d85ef889b0c86cb73b6998b106d to your computer and use it in GitHub Desktop.
Serialize Kotlin data class constructor fields based on @JsonProperty annotations into string json. Nested non primitive fields will be serialized also but without any Annotations driving
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.toJsonV2(): String { | |
var fieldNameToAnnotatedNameMap = [email protected] { it.name }.associateWith { fieldName -> | |
val jsonFieldName = | |
this@toJsonV2::class.primaryConstructor?.parameters?.first { it.name == fieldName }?.annotations?.firstOrNull { it is JsonProperty } | |
val serializedName = if (jsonFieldName != null) (jsonFieldName as JsonProperty).value else fieldName | |
serializedName | |
} | |
return buildString { | |
append("{\n") | |
fieldNameToAnnotatedNameMap.entries.forEach { e -> | |
val field = this@toJsonV2::class.memberProperties.first { it.name == e.key } | |
var value = field.javaGetter?.invoke(this@toJsonV2) | |
if (value?.javaClass?.isPrimitive != true) | |
value = value?.toJson() | |
append("\"${e.value}\": $value") | |
if (fieldNameToAnnotatedNameMap.entries.indexOf(e) != fieldNameToAnnotatedNameMap.entries.size-1) | |
append(",\n") | |
} | |
append("\n}") | |
} | |
} | |
fun Any.toJson(pretty: Boolean = false, sortAbc: Boolean = false): String { | |
val objectMapper = ObjectMapper() | |
if (sortAbc) objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY) | |
if (pretty) { | |
objectMapper.enable(SerializationFeature.INDENT_OUTPUT) | |
return objectMapper.writeValueAsString(this) | |
} | |
return objectMapper.writeValueAsString(this).trimIndent() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment