Skip to content

Instantly share code, notes, and snippets.

@lsoares
Last active October 16, 2019 21:59
Show Gist options
  • Save lsoares/f4ead474b247c226a8a8fdd8e93aad3d to your computer and use it in GitHub Desktop.
Save lsoares/f4ead474b247c226a8a8fdd8e93aad3d to your computer and use it in GitHub Desktop.
toJson
fun <V> Map<String, V>.toJson() = convertObject(this)
private fun <V> convertObject(map: Map<String, V>) =
"{ " + map.entries.joinToString(", ") { "\"${it.key}\": ${convertValue(it.value)}" } + " }"
private fun <V> convertValue(value: V): String = when (value) {
is String -> "\"$value\""
is List<*> -> "[ " + value.joinToString(", ") { convertValue(it) } + " ]"
is Map<*, *> -> convertObject(value as Map<String, V>)
else -> value.toString()
}
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
object MapToJsonTest {
@Test
fun `test integer`() {
assertEquals("""{ "a": 1 }""", mapOf("a" to 1).toJson())
}
@Test
fun `test float`() {
assertEquals("""{ "a": 1.1 }""", mapOf("a" to 1.1).toJson())
}
@Test
fun `test null`() {
assertEquals("""{ "a": null }""", mapOf("a" to null).toJson())
}
@Test
fun `test bool`() {
assertEquals("""{ "a": false }""", mapOf("a" to false).toJson())
}
@Test
fun `test str`() {
assertEquals("""{ "a": "str" }""", mapOf("a" to "str").toJson())
}
@Test
fun `test array`() {
assertEquals("""{ "a": [ 1, 2, 3 ] }""", mapOf("a" to listOf(1, 2, 3)).toJson())
}
@Test
fun `test inner obj`() {
val obj = mapOf(
"a" to mapOf(
"b" to 1
)
)
assertEquals("""{ "a": { "b": 1 } }""", obj.toJson())
}
@Test
fun `test array of objects`() {
val obj = mapOf(
"arr" to listOf(
mapOf("x" to 1, "y" to 2),
mapOf("z" to 3)
)
)
assertEquals("""{ "arr": [ { "x": 1, "y": 2 }, { "z": 3 } ] }""", obj.toJson())
}
@Test
fun `test complex obj`() {
val obj = mapOf(
"aString" to "str",
"anObject" to mapOf(
"bool1" to true,
"theOther" to false
),
"anArray" to listOf(1, 3),
"imNull" to null
)
assertEquals(
"""{ "aString": "str", "anObject": { "bool1": true, "theOther": false }, "anArray": [ 1, 3 ], "imNull": null }""",
obj.toJson()
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment