Skip to content

Instantly share code, notes, and snippets.

@90K2
Created August 10, 2022 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 90K2/fbeb8d85ef889b0c86cb73b6998b106d to your computer and use it in GitHub Desktop.
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
fun Any.toJsonV2(): String {
var fieldNameToAnnotatedNameMap = this@toJsonV2.javaClass.declaredFields.map { 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