https://kotlinlang.org logo
#feed
Title
# feed
h

Hitanshu Dhawan

10/30/2019, 1:43 AM
JsonDSL It is a DSL in Kotlin for creating your JSON in a more easy and readable way. Do check it out! https://github.com/hitanshu-dhawan/JsonDSL
👎 3
👍 9
🤔 5
c

czuckie

10/30/2019, 2:03 PM
Copy code
import 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 paste
😅 3
h

Hitanshu Dhawan

10/30/2019, 2:28 PM
Yes, that's the beauty of writing DSLs in Kotlin. Wanted to make a separate library so that we don't have deal with copy-paste in new file. Just a simple gradle dependency would work.
d

Derek Peirce

10/31/2019, 6:42 AM
My main concern is that you're overloading
to
. 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).
2
h

Hitanshu Dhawan

10/31/2019, 6:48 AM
Yes, fair points Derek. Thanks a lot for having a look at my library and providing your valuable inputs. Will surely fix these issues in the coming next release. Thanks again.
72 Views