Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active May 14, 2018
Embed
What would you like to do?
fun <A> A.toJson(): String {
fun <A> Iterable<A>.toJsonArray(): String =
joinToString(", ", "[", "]") { it.toJson() }
fun <A, B> Map<A, B>.toJsonObject() =
entries.joinToString(", ", "{", "}") { (key, value) -> "\"$key\" : ${value.toJson()}" }
return when(this) {
null -> "null"
is String -> "\"$this\""
is Array<*> -> this.toList().toJsonArray()
is Iterable<*> -> this.toJsonArray()
is Map<*, *> -> this.toJsonObject()
else -> toString()
}
}
val json = mapOf("users" to names.toList().map {
mapOf(
"name" to "No name",
"id" to it,
"avatar_url" to "https://gravatar.com/img/2124"
)
}).toJson()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment