-
-
Save PaulWoitaschek/84cf08b07abc56e4c43a2b7ec0b43508 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.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