Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method toJson() to class BsonArray. #1284

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion bson/src/main/org/bson/AbstractBsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ public void writeStartArray(final String name) {

@Override
public void writeStartArray() {
checkPreconditions("writeStartArray", State.VALUE);
checkPreconditions("writeStartArray", State.INITIAL, State.VALUE, State.SCOPE_DOCUMENT, State.DONE);

if (context != null && context.name != null) {
fieldNameValidatorStack.push(fieldNameValidatorStack.peek().getValidatorForField(getName()));
Expand Down
30 changes: 27 additions & 3 deletions bson/src/main/org/bson/BsonArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.bson.codecs.DecoderContext;
import org.bson.json.JsonReader;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -234,11 +235,34 @@ public int hashCode() {
return values.hashCode();
}

/**
* Gets a JSON representation of this array using the {@link org.bson.json.JsonMode#RELAXED} output mode, and otherwise the default
* settings of {@link JsonWriterSettings.Builder}.
*
* @return a JSON representation of this array
* @see #toJson(JsonWriterSettings)
* @see JsonWriterSettings
*/
public String toJson() {
return toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
}

/**
* Gets a JSON representation of this array using the given
* {@code JsonWriterSettings}.
*
* @param settings the JSON writer settings
* @return a JSON representation of this array
*/
public String toJson(final JsonWriterSettings settings) {
StringWriter writer = new StringWriter();
new BsonArrayCodec().encode(new JsonWriterExt(writer, settings), this, EncoderContext.builder().build());
return writer.toString();
}

@Override
public String toString() {
return "BsonArray{"
+ "values=" + getValues()
+ '}';
return this.toJson();
}

@Override
Expand Down