<@U5EFLTPJ5> Hi, what it the name of that JSON Bui...
# codingconventions
h
@efemoney Hi, what it the name of that JSON Builder DSL?
e
Its a custom builder using Gson's
JsonObject
under the hood.
Copy code
class JsonBuilder {
  private val json = JsonObject()

  infix fun <T : JsonElement> <http://String.to|String.to>(value: T) = json.add(this, value)
  infix fun <http://String.to|String.to>(value: Char) = json.addProperty(this, value)
  infix fun <http://String.to|String.to>(value: String) = json.addProperty(this, value)
  infix fun <http://String.to|String.to>(value: CharSequence) = json.addProperty(this, value.toString())
  infix fun <http://String.to|String.to>(value: Number) = json.addProperty(this, value)
  infix fun <http://String.to|String.to>(value: Boolean) = json.addProperty(this, value)

  fun build(): JsonObject = json
}

class JsonArrayBuilder {
  private val json = JsonArray()

  operator fun <T : JsonElement> T.unaryPlus() = json.add(this)
  operator fun Char.unaryPlus() = json.add(this)
  operator fun String.unaryPlus() = json.add(this)
  operator fun CharSequence.unaryPlus() = json.add(this.toString())
  operator fun Number.unaryPlus() = json.add(this)
  operator fun Boolean.unaryPlus() = json.add(this)

  fun build(): JsonArray = json
}

fun obj(builder: JsonBuilder.() -> Unit) = JsonBuilder().apply(builder).build()

fun arr(builder: JsonArrayBuilder.() -> Unit) = JsonArrayBuilder().apply(builder).build()
👍 4
Could've used
Map
and/or `List`s however