Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active May 14, 2018 14:00
Show Gist options
  • Save pablisco/b929e00b8011199481910328b4fa9fd9 to your computer and use it in GitHub Desktop.
Save pablisco/b929e00b8011199481910328b4fa9fd9 to your computer and use it in GitHub Desktop.
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