Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Created April 11, 2024 21:43
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 MarkTiedemann/ff5174259927ac3b68622d189232c0e1 to your computer and use it in GitHub Desktop.
Save MarkTiedemann/ff5174259927ac3b68622d189232c0e1 to your computer and use it in GitHub Desktop.
Kotlin toJson Extensions
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))}"
}
}}"
}
@MarkTiedemann
Copy link
Author

TODO: Throw on circular references (or max. depth)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment