How can I convert a Java (/Scala) BsonArray
to a json string?
If I have
val array = new BsonArray()
array.add(new BsonInt32(1))
array.add(new BsonInt32(2))
it would be nice if "array.toJson" gave me
"[1, 2]"
But BsonArray
has no toJson
method. So what could I do instead?
The real content of my array is more complex (nested documents) and I need to pretty-print it with indentations.
When I need to convert a BsonDocument
I can call its toJson
method
val doc = new BsonDocument()
// ..populate doc..
val pretty = JsonWriterSettings.builder().indent(true).build()
doc.toJson(pretty)
This can be done in a hacky way by creating a temporary
BsonDocument
object with theBsonArray
object as its value, converting theBsonDocument
to JSON and then extracting out the part corresponding to theBsonArray
from the output JSON string. Something like the below:You could also build the JSON yourself using a method like the below, but it might end up being a little too long and complicated(even before pretty print) if you need to handle all
BsonValue
types.