Created
April 11, 2024 21:43
-
-
Save MarkTiedemann/ff5174259927ac3b68622d189232c0e1 to your computer and use it in GitHub Desktop.
Kotlin toJson Extensions
This file contains hidden or 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
private fun convertToJson(v: Any?): String { | |
return when (v) { | |
is String -> v.toJson() | |
is Boolean -> v.toJson() | |
is Number -> v.toJson() | |
is Array<*> -> v.toJson() | |
is Collection<*> -> v.toJson() | |
is Map<*, *> -> v.toJson() | |
else -> v?.toJson() ?: "null" | |
} | |
} | |
fun String.toJson(): String = "\"${this.replace("\"", "\\\"")}\"" | |
fun Boolean.toJson(): String = if (this) "true" else "false" | |
fun Number.toJson(): String = this.toString() | |
fun Array<*>.toJson(): String = "[${this.joinToString(",") { convertToJson(it) }}]" | |
fun Collection<*>.toJson(): String = "[${this.joinToString(",") { convertToJson(it) }}]" | |
fun Map<*, *>.toJson(): String { | |
return "{${ | |
this.entries.joinToString(",") { | |
"\"${ | |
if (it.key is String || it.key is Boolean || it.key is Number) it.key!!.toJson() | |
else "__not_a_primitive__" | |
}\":${convertToJson(it.value)}" | |
} | |
}}" | |
} | |
fun Any.toJson(): String { | |
return if (!this::class.isData) | |
"{\"__not_a_data_class__\":\"${this::class.qualifiedName}\"}" | |
else "{${ | |
this.javaClass.declaredFields.joinToString(",") { | |
it.isAccessible = true | |
"\"${it.name}\":${convertToJson(it.get(this))}" | |
} | |
}}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: Throw on circular references (or max. depth)