Closed
Description
What is your use-case and why do you need this feature?
When building a JSON array I'd like to add multiple strings.
Currently this must be done one at a time, using JsonArrayBuilder.add(value: String?)
val alphaDependencies = listOf("a", "b", "c")
buildJsonObject {
put("name", "alpha")
putJsonArray("dependencies") {
// currently have to manually define a for-loop
alphaDependencies.forEach { dep ->
add(dep)
}
}
}.toString()
It's a surprise that buildJsonArray()
doesn't have addAll()
, because buildList()
does have addAll()
.
val x = listOf('b', 'c')
val y = buildList() {
addAll(x)
}
Describe the solution you'd like
It would be convenient to have an addAll(elements: Collection<String>)
helper function that would accept a list
I'm proposing four new functions.
1 function in JsonArrayBuilder
for adding multiple JsonElement
s.
public class JsonArrayBuilder @PublishedApi internal constructor() {
/**
* Adds the given JSON [elements] to a resulting JSON array.
*
* @return `true` if the list was changed as the result of the operation.
*/
public fun addAll(elements: Collection<JsonElement>): Boolean {
return content.addAll(elements)
}
}
And 3 extension functions, for adding strings, numbers, booleans:
/** Adds the given string [values] to a resulting JSON array. */
public fun JsonArrayBuilder.addAll(values: Collection<String?>): Boolean =
addAll(values.map(::JsonPrimitive))
/** Adds the given boolean [values] to a resulting JSON array. */
public fun JsonArrayBuilder.addAll(values: Collection<Boolean?>): Boolean =
addAll(values.map(::JsonPrimitive))
/** Adds the given numeric [values] to a resulting JSON array. */
public fun JsonArrayBuilder.addAll(values: Collection<Number?>): Boolean =
addAll(values.map(::JsonPrimitive))
Example usage
buildJsonObject {
put("name", "alpha")
putJsonArray("dependencies") {
// no more need for a for loop
addAll(alphaDependencies)
}
}.toString()