Last active
November 13, 2019 11:42
-
-
Save CanerPatir/cd55088d8738cc7c9524a28ac2b1cb37 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fun json(init: Json.() -> Unit): Json { | |
| val json = Json() | |
| json.init() | |
| return json | |
| } | |
| open class Json { | |
| private val entries: LinkedHashMap<String, Any> = linkedMapOf() | |
| infix fun String.to(value: Any): Unit { | |
| entries[this] = value | |
| } | |
| infix fun obj(init: Json.() -> Unit): Json { | |
| val obj = Json() | |
| obj.init() | |
| return obj | |
| } | |
| fun render(indent: String = " "): String { | |
| val sb = StringBuilder().append("{").append("\n") | |
| for ((k, v) in entries) { | |
| with(sb) { | |
| append("""$indent"$k" : """) | |
| when (v) { | |
| is String -> append(""""$v"""") | |
| is Array<*> -> append("[${v.joinToString()}]") | |
| is Json -> append(v.render()) | |
| else -> append("$v") | |
| } | |
| if (entries.entries.last().value != v) { | |
| append(",") | |
| } | |
| append("\n") | |
| } | |
| } | |
| sb.append("$indent}") | |
| return sb.toString() | |
| } | |
| } | |
| fun main(){ | |
| val jsonStr = json { | |
| "properties" to obj { | |
| "campaignId" to obj { | |
| "type" to "long" | |
| } | |
| "eventType" to obj { | |
| "type" to "keyword" | |
| } | |
| "correlationId" to obj { | |
| "type" to "keyword" | |
| } | |
| "userEmail" to obj { | |
| "type" to "keyword" | |
| } | |
| "agentName" to obj { | |
| "type" to "keyword" | |
| } | |
| "timeStamp" to obj { | |
| "type" to "date" | |
| } | |
| "detail" to obj { | |
| "type" to "text" | |
| } | |
| } | |
| }.render() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment