Skip to content

Instantly share code, notes, and snippets.

@venator85
Created November 19, 2024 15:31
Show Gist options
  • Save venator85/bdf2012e6c500c0d4dc2c9d9478a43e5 to your computer and use it in GitHub Desktop.
Save venator85/bdf2012e6c500c0d4dc2c9d9478a43e5 to your computer and use it in GitHub Desktop.
Kotlin JSON DSL
import org.json.JSONArray
import org.json.JSONObject
class Json() : JSONObject() {
constructor(init: Json.() -> Unit) : this() {
this.init()
}
infix fun Any.to(json: Json.() -> Unit) {
if (this !is String) throw UnsupportedOperationException("keys must be string: $this")
put(this, Json().apply(json))
}
infix fun <T> Any.to(value: T) {
if (this !is String) throw UnsupportedOperationException("keys must be string: $this")
put(this, value)
}
infix fun <T> Any.to(values: List<T>) {
val key = this
if (key !is String) throw UnsupportedOperationException("keys must be string: $key")
put(key, JSONArray().apply {
values.forEach {
if (it is Function0<*>) {
throw UnsupportedOperationException("Use 'Json {...}' syntax instead of '{...}' for json objects in array '$key'")
} else {
put(it)
}
}
})
}
}
val example = Json {
"a" to "aa"
"b" to 1
"c" to 3.14
"d" to false
"e" to null
"f" to Json {
"a" to "b"
}
"g" to listOf(
Json {
"a" to "b"
},
"23",
3,
false,
null
)
"h" to {
"a" to "b"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment