Skip to content

Instantly share code, notes, and snippets.

@DevSrSouza
Created January 30, 2019 16:09
Show Gist options
  • Save DevSrSouza/600456508b4a197531598ce1a8ca4549 to your computer and use it in GitHub Desktop.
Save DevSrSouza/600456508b4a197531598ce1a8ca4549 to your computer and use it in GitHub Desktop.
A json DSL builder for google gson library.
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
@DslMarker
annotation class JsonMarker
@JsonMarker
fun json(block: JsonObjectBuilder.() -> Unit): JsonObject {
return JsonObjectBuilder().apply(block).element
}
interface JsonBuilder<T : JsonElement> {
val element: T
}
class JsonObjectBuilder : JsonBuilder<JsonObject> {
override val element = JsonObject()
infix fun String.value(n: Number) { element.addProperty(this, n) }
infix fun String.value(b: Boolean) { element.addProperty(this, b) }
infix fun String.value(str: String) { element.addProperty(this, str) }
infix fun String.value(c: Char) { element.addProperty(this, c) }
infix fun String.value(json: JsonObject) { element.add(this, json) }
infix fun String.value(array: JsonArray) { element.add(this, array) }
@JsonMarker
fun array(block: JsonArrayBuilder.() -> Unit) = JsonArrayBuilder().apply(block).element
}
class JsonArrayBuilder : JsonBuilder<JsonArray> {
override val element = JsonArray()
operator fun String.unaryPlus() { element.add(JsonPrimitive(this)) }
operator fun Boolean.unaryPlus() { element.add(JsonPrimitive(this)) }
operator fun Number.unaryPlus() { element.add(JsonPrimitive(this)) }
operator fun Char.unaryPlus() { element.add(JsonPrimitive(this)) }
fun add(str: String) { +str }
fun add(bool: Boolean) { +bool }
fun add(number: Number) { +number }
fun add(char: Char) { +char }
@JsonMarker
fun json(block: JsonObjectBuilder.() -> Unit) {
element.add(JsonObjectBuilder().apply(block).element)
}
@JsonMarker
fun array(block: JsonArrayBuilder.() -> Unit) = element.add(JsonArrayBuilder().apply(block).element)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment