Updated version of my Json building DSL. Feedback ...
# codereview
d
Updated version of my Json building DSL. Feedback requested. README.md
Copy code
import com.stochastictinkr.json.*

fun main() {
    val obj = jsonObject {
        "name"("John Doe")
        "age"(25)
        "address" {
            "number"(123)
            "street"("Main Street")
            "city"("Anytown")
            "state"("AS")
            "zip"(12345)
        }
        "phoneNumbers"[{
            add("555-1234")
            add("555-5678")
        }]
        "favoriteColor"(null)
        "averageScore"(85.5)
    }
    println(JsonWriter.Pretty.writeToString(obj))
}
Resulting JSON:
Copy code
{
  "name": "John Doe",
  "age": 25,
  "address": {
    "number": 123,
    "street": "Main Street",
    "city": "Anytown",
    "state": "AS",
    "zip": 12345
  },
  "phoneNumbers": [
    "555-1234",
    "555-5678"
  ],
  "favoriteColor": null,
  "averageScore": 85.5
}
@CLOVIS You had some really good feedback last time.
c
Oh, that's an interesting one 🤔
I usually avoid
String.invoke()
because it's very easy to do weird things with, but that seems like a good case 🤔 I probably would've went with
Copy code
jsonObject {
    "name" set "John Doe"
    "age" set 25
    // …
}
but that's personal preference I think
It's nice that you scoped the operators to a DSL interface, this way people don't need to import them + they don't pollute the scope
k
I think this will become much nicer when we get collection literals in Kotlin (KT-43871).
d
add(...)
could be
+"..."
maybe (like in kotlinx html)
c
It could, but should it? 😅
d
Well...
"..."(...)
vs
"..." set ...
and
+"..."
vs
add(...)
... 😁. Not that I have any particular preference here... just seems more consistent.
d
For what it’s worth, JsonArray implements MutableList<JsonElement> and JsonObject implements MutableMap<String, JsonElement>. As for + vs add, I’m a bit torn on that. I feel like it’s more likely to be confusing with numeric literals. It’s kind of too bad I couldn’t use a custom
:
operator for the object keys.
d
yeah numeric values wouldn't be too nice with that syntax... you're right.