Hitanshu Dhawan
10/30/2019, 1:43 AMczuckie
10/30/2019, 2:03 PMimport org.json.JSONArray
import org.json.JSONObject
fun json(block: JSONObjectBuilder.() -> Unit) = JSONObjectBuilder().apply(block).json
class JSONObjectBuilder {
val json = JSONObject()
infix fun <http://String.to|String.to>(value: Any?) {
json.put(this, value ?: JSONObject.NULL)
}
}
fun jsonArray(vararg values: Any?): JSONArray {
val jsonArray = JSONArray()
for (value in values)
jsonArray.put(value ?: JSONObject.NULL)
return jsonArray
}
The entire library in a single pasteHitanshu Dhawan
10/30/2019, 2:28 PMDerek Peirce
10/31/2019, 6:42 AMto
. If someone mistakenly uses a non-string key, it will silently be ignored. Separately, if someone uses a non-JSON value, it's caught at runtime instead of compile-time, even though you could instead limit value
to only a few types (Number?
, String?
, Boolean?
, JSONArray?
, or JSONObject?
, plus maybe Character
, I guess).Hitanshu Dhawan
10/31/2019, 6:48 AM