klaxon
klaxon copied to clipboard
Kotlin DSL documented example doesn't work
Looking at the example provided in the README.md
:
val obj = json {
repeat(3) {
put("field$it", it * 2)
}
}
It throws a java.util.EmptyStackException
.
There seems to be no way for me to use put()
to make a flat, single level JSON. Something like this:
{
"a": "b",
"c": "d"
}
Note, I need to generate the contents procedurally, so working with put()
will be better than passing a collection of Pair<String, *>
Indeed, the examples don't work because the returned value of the json {}
function are not valid objects.
The following examples should work.
val obj = json { obj(
"color" to "red",
"age" to 23
)}
/*
{
"color":"red",
"age":23
}
*/
If you want to populate a nested object:
val obj = json { obj("fields") {
repeat(3) {
put("field$it", it * 2)
}
}
}
/*
{
"fields": {
"field0": 0,
"field1": 2,
"field2": 4
}
}
*/
If you want to populate the root object, it is ugly, but currently seems to be the working option:
val obj = json {
val o = obj()
o.repeat(3) {
put("field$it", it * 2)
}
o // Return the object
}
/*
{
"field0": 0,
"field1": 2,
"field2": 4
}
*/