Skip to content

Instantly share code, notes, and snippets.

@westonal
Created January 5, 2022 04:59
Show Gist options
  • Save westonal/2f7fe097fd89ebabe289e65dbaecb3b6 to your computer and use it in GitHub Desktop.
Save westonal/2f7fe097fd89ebabe289e65dbaecb3b6 to your computer and use it in GitHub Desktop.
Kotlin Json Dsl idea
package com.example
import kotlinx.serialization.json.*
import org.junit.Assert.assertEquals
import org.junit.Test
class JsonDslTest {
@Test
fun `declare complex object`() {
val json = jsonObject {
"booleanKey" += true
"arrayKey" += 1..10
"objectKey" += jsonObject {
"stringKey" += "stringValue"
}
"objectArray" += arrayOf(jsonObject {
"intKey" += 123
})
}
assertEquals(
"""{"booleanKey":true,"arrayKey":[1,2,3,4,5,6,7,8,9,10],"objectKey":{"stringKey":"stringValue"},"objectArray":[{"intKey":123}]}""",
json.toString()
)
}
}
fun jsonObject(function: Builder.() -> Unit): JsonObject = buildJsonObject {
Builder(this).apply(function)
}.jsonObject
class Builder(val builder: JsonObjectBuilder) {
infix operator fun String.plusAssign(value: Boolean) {
builder.put(this, value)
}
infix operator fun String.plusAssign(value: Number) {
builder.put(this, value)
}
infix operator fun String.plusAssign(value: String) {
builder.put(this, value)
}
infix operator fun String.plusAssign(value: JsonObject) {
builder.put(this, value)
}
infix operator fun String.plusAssign(value: Array<Boolean>) {
builder.put(this, buildJsonArray {
value.forEach {
this.add(it)
}
})
}
infix operator fun String.plusAssign(value: Iterable<Number>) {
builder.put(this, buildJsonArray {
value.forEach {
this.add(it)
}
})
}
infix operator fun String.plusAssign(value: Array<String>) {
builder.put(this, buildJsonArray {
value.forEach {
this.add(it)
}
})
}
infix operator fun String.plusAssign(value: Array<JsonObject>) {
builder.put(this, buildJsonArray {
value.forEach {
this.add(it)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment