Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Created December 1, 2021 22:28
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/84cf08b07abc56e4c43a2b7ec0b43508 to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/84cf08b07abc56e4c43a2b7ec0b43508 to your computer and use it in GitHub Desktop.
fun JsonElement.appendTo(builder: StringBuilder) {
when (this) {
is JsonArray -> {
builder.append("[")
elements.forEachIndexed { index, element ->
element.appendTo(builder)
if (index != elements.size - 1) {
builder.append(",")
}
}
builder.append("]")
}
is JsonBoolean -> {
builder.append(value)
}
JsonNull -> {
builder.append("null")
}
is JsonNumber -> {
var valueFormatted = value.toString()
if ('.' in valueFormatted) {
valueFormatted = value.toString().dropLastWhile { it == '0' }
.dropLastWhile { it == '.' }
}
builder.append(valueFormatted)
}
is JsonObject -> {
builder.append("{")
fields.toList().forEachIndexed { index, (key, value) ->
builder.append("\"${key}\":")
value.appendTo(builder)
if (index != fields.size - 1) {
builder.append(",")
}
}
builder.append("}")
}
is JsonString -> {
builder.append("\"$value\"")
}
}
}
fun JsonElement.stringify(): String {
val builder = StringBuilder()
appendTo(builder)
return builder.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment