-
-
Save PaulWoitaschek/6526ee2397e8d67fa56f5182a3aa492a to your computer and use it in GitHub Desktop.
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 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