Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Created December 1, 2021 22:35
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 PaulWoitaschek/6526ee2397e8d67fa56f5182a3aa492a to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/6526ee2397e8d67fa56f5182a3aa492a to your computer and use it in GitHub Desktop.
fun JsonElement.stringify(): String {
return when (this) {
is JsonArray -> {
elements.joinToString(prefix = "[", postfix = "]", separator = ",") {
it.stringify()
}
}
is JsonBoolean -> value.toString()
JsonNull -> "null"
is JsonNumber -> {
val valueFormatted = value.toString()
if ('.' in valueFormatted) {
value.toString().dropLastWhile { it == '0' }.dropLastWhile { it == '.' }
} else {
valueFormatted
}
}
is JsonObject -> {
fields.toList().joinToString(prefix = "{", postfix = "}", separator = ",") { (key, value) ->
"\"${key}\":${value.stringify()}"
}
}
is JsonString -> {
"\"$value\""
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment