CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-mongodb--bson

The BSON library for MongoDB Java Driver - A high-performance binary serialization format and library for MongoDB documents

Pending
Overview
Eval results
Files

json.mddocs/

JSON Conversion

The BSON JSON support provides comprehensive conversion between BSON documents and JSON strings. It supports multiple JSON output formats including MongoDB Extended JSON, strict JSON, and shell format, with configurable settings for different use cases.

JSON Reader

The JsonReader class reads JSON strings and converts them to BSON values.

public class JsonReader extends AbstractBsonReader {
    /**
     * Constructs a new instance which reads from the given string.
     * @param json a JSON string
     */
    public JsonReader(String json);
    
    /**
     * Constructs a new instance which reads from the given Reader.
     * @param reader a Reader containing JSON
     */
    public JsonReader(Reader reader);
    
    /**
     * Constructs a new instance which reads from the given string using the given settings.
     * @param json a JSON string
     * @param settings the read settings
     */
    public JsonReader(String json, JsonReaderSettings settings);
    
    /**
     * Constructs a new instance which reads from the given Reader using the given settings.
     * @param reader a Reader containing JSON
     * @param settings the read settings
     */
    public JsonReader(Reader reader, JsonReaderSettings settings);
    
    // Implementation of BsonReader interface
    public BsonType readBsonType();
    public String readName();
    public void skipName();
    public void skipValue();
    public BsonBinary readBinaryData();
    public boolean readBoolean();
    public long readDateTime();
    public double readDouble();
    public int readInt32();
    public long readInt64();
    public Decimal128 readDecimal128();
    public String readJavaScript();
    public String readJavaScriptWithScope();
    public void readMaxKey();
    public void readMinKey();
    public void readNull();
    public ObjectId readObjectId();
    public BsonRegularExpression readRegularExpression();
    public String readString();
    public String readSymbol();
    public BsonTimestamp readTimestamp();
    public void readUndefined();
    public void readStartArray();
    public void readEndArray();
    public void readStartDocument();
    public void readEndDocument();
    public void close();
}

JSON Writer

The JsonWriter class writes BSON values as JSON strings.

public class JsonWriter extends AbstractBsonWriter {
    /**
     * Constructs a new instance which writes to the given writer.
     * @param writer a Writer to write JSON to
     */
    public JsonWriter(Writer writer);
    
    /**
     * Constructs a new instance which writes to the given writer and uses the given settings.
     * @param writer a Writer to write JSON to
     * @param settings the settings to apply to this writer
     */
    public JsonWriter(Writer writer, JsonWriterSettings settings);
    
    /**
     * Constructs a new instance which writes to the given StringWriter.
     * @param stringWriter a StringWriter to write JSON to
     */
    public JsonWriter(StringWriter stringWriter);
    
    /**
     * Constructs a new instance which writes to the given StringWriter and uses the given settings.
     * @param stringWriter a StringWriter to write JSON to
     * @param settings the settings to apply to this writer
     */
    public JsonWriter(StringWriter stringWriter, JsonWriterSettings settings);
    
    // Implementation of BsonWriter interface
    public void writeBinaryData(BsonBinary binary);
    public void writeBoolean(boolean value);
    public void writeDateTime(long value);
    public void writeDouble(double value);
    public void writeInt32(int value);
    public void writeInt64(long value);
    public void writeDecimal128(Decimal128 value);
    public void writeJavaScript(String code);
    public void writeJavaScriptWithScope(String code);
    public void writeMaxKey();
    public void writeMinKey();
    public void writeName(String name);
    public void writeNull();
    public void writeObjectId(ObjectId objectId);
    public void writeRegularExpression(BsonRegularExpression regularExpression);
    public void writeString(String value);
    public void writeSymbol(String value);
    public void writeTimestamp(BsonTimestamp value);
    public void writeUndefined();
    public void writeStartArray();
    public void writeEndArray();
    public void writeStartDocument();
    public void writeEndDocument();
    public void flush();
    public void close();
}

JSON Reader Settings

public final class JsonReaderSettings {
    /**
     * Gets the maximum length of JSON strings to parse.
     * @return the maximum length
     */
    public int getMaxLength();
    
    /**
     * Creates a builder for JsonReaderSettings.
     * @return the builder
     */
    public static Builder builder();
    
    public static final class Builder {
        /**
         * Sets the maximum length of JSON strings to parse.
         * @param maxLength the maximum length
         * @return this
         */
        public Builder maxLength(int maxLength);
        
        /**
         * Build the settings.
         * @return the settings
         */
        public JsonReaderSettings build();
    }
}

JSON Writer Settings

public final class JsonWriterSettings {
    /**
     * Gets the output mode for JSON formatting.
     * @return the output mode
     */
    public JsonMode getOutputMode();
    
    /**
     * Gets whether output should be indented.
     * @return true if output should be indented
     */
    public boolean isIndent();
    
    /**
     * Gets the indent characters.
     * @return the indent characters
     */
    public String getIndentCharacters();
    
    /**
     * Gets the new line characters.
     * @return the new line characters
     */
    public String getNewLineCharacters();
    
    /**
     * Gets the maximum length of the JSON representation of a string.
     * @return the maximum length
     */
    public int getMaxLength();
    
    /**
     * Gets the DateTimeFormatter for formatting date/time values.
     * @return the DateTimeFormatter
     */
    public DateTimeFormatter getDateTimeFormatter();
    
    /**
     * Gets the converter for BsonBinary values.
     * @return the converter
     */
    public Converter<BsonBinary> getBinaryConverter();
    
    /**
     * Gets the converter for BsonBoolean values.
     * @return the converter
     */
    public Converter<BsonBoolean> getBooleanConverter();
    
    /**
     * Gets the converter for BsonDateTime values.
     * @return the converter
     */
    public Converter<BsonDateTime> getDateTimeConverter();
    
    /**
     * Gets the converter for BsonDecimal128 values.
     * @return the converter
     */
    public Converter<BsonDecimal128> getDecimal128Converter();
    
    /**
     * Gets the converter for BsonDouble values.
     * @return the converter
     */
    public Converter<BsonDouble> getDoubleConverter();
    
    /**
     * Gets the converter for BsonInt32 values.
     * @return the converter
     */
    public Converter<BsonInt32> getInt32Converter();
    
    /**
     * Gets the converter for BsonInt64 values.
     * @return the converter
     */
    public Converter<BsonInt64> getInt64Converter();
    
    /**
     * Gets the converter for BsonObjectId values.
     * @return the converter
     */
    public Converter<BsonObjectId> getObjectIdConverter();
    
    /**
     * Gets the converter for BsonString values.
     * @return the converter
     */
    public Converter<BsonString> getStringConverter();
    
    /**
     * Creates a builder for JsonWriterSettings.
     * @return the builder
     */
    public static Builder builder();
    
    public static final class Builder {
        /**
         * Sets the output mode.
         * @param outputMode the output mode
         * @return this
         */
        public Builder outputMode(JsonMode outputMode);
        
        /**
         * Sets whether output should be indented.
         * @param indent true if output should be indented
         * @return this
         */
        public Builder indent(boolean indent);
        
        /**
         * Sets the indent characters.
         * @param indentCharacters the indent characters
         * @return this
         */
        public Builder indentCharacters(String indentCharacters);
        
        /**
         * Sets the new line characters.
         * @param newLineCharacters the new line characters
         * @return this
         */
        public Builder newLineCharacters(String newLineCharacters);
        
        /**
         * Sets the maximum length of the JSON representation.
         * @param maxLength the maximum length
         * @return this
         */
        public Builder maxLength(int maxLength);
        
        /**
         * Sets the DateTimeFormatter for date/time formatting.
         * @param dateTimeFormatter the DateTimeFormatter
         * @return this
         */
        public Builder dateTimeFormatter(DateTimeFormatter dateTimeFormatter);
        
        /**
         * Sets the converter for BsonBinary values.
         * @param binaryConverter the converter
         * @return this
         */
        public Builder binaryConverter(Converter<BsonBinary> binaryConverter);
        
        /**
         * Sets the converter for BsonDateTime values.
         * @param dateTimeConverter the converter
         * @return this
         */
        public Builder dateTimeConverter(Converter<BsonDateTime> dateTimeConverter);
        
        /**
         * Sets the converter for BsonDecimal128 values.
         * @param decimal128Converter the converter
         * @return this
         */
        public Builder decimal128Converter(Converter<BsonDecimal128> decimal128Converter);
        
        /**
         * Sets the converter for BsonObjectId values.
         * @param objectIdConverter the converter
         * @return this
         */
        public Builder objectIdConverter(Converter<BsonObjectId> objectIdConverter);
        
        /**
         * Build the settings.
         * @return the settings
         */
        public JsonWriterSettings build();
    }
}

JSON Output Modes

public enum JsonMode {
    /**
     * Strict mode produces output that conforms to the JSON RFC.
     * For BSON types that do not have a JSON equivalent, it uses the "canonical" extended JSON representation.
     */
    STRICT,
    
    /**
     * Extended mode produces output that conforms to the MongoDB Extended JSON specification.
     * This is the most compact representation while preserving type information.
     */
    EXTENDED,
    
    /**
     * Relaxed mode produces output that is more readable and JavaScript-compatible.
     * Some BSON type information may be lost.
     */
    RELAXED,
    
    /**
     * Shell mode produces output that can be parsed by the MongoDB shell.
     */
    SHELL
}

JSON Converters

public interface Converter<T> {
    /**
     * Convert the given value to a string.
     * @param value the value to convert
     * @return the string representation
     */
    void convert(T value, StrictJsonWriter writer);
}

public final class StrictJsonWriter {
    /**
     * Writes a raw JSON value.
     * @param json the JSON string
     */
    public void writeRaw(String json);
    
    /**
     * Writes a string value.
     * @param value the string value
     */
    public void writeString(String value);
    
    /**
     * Writes a number value.
     * @param value the number value
     */
    public void writeNumber(String value);
    
    /**
     * Writes a boolean value.
     * @param value the boolean value
     */
    public void writeBoolean(boolean value);
    
    /**
     * Writes a null value.
     */
    public void writeNull();
    
    /**
     * Writes the start of an object.
     */
    public void writeStartObject();
    
    /**
     * Writes the end of an object.
     */
    public void writeEndObject();
    
    /**
     * Writes the start of an array.
     */
    public void writeStartArray();
    
    /**
     * Writes the end of an array.
     */
    public void writeEndArray();
    
    /**
     * Writes a field name.
     * @param name the field name
     */
    public void writeName(String name);
}

Built-in JSON Converters

public final class JsonConverters {
    /**
     * A converter that writes ObjectId values in strict JSON format.
     */
    public static final Converter<BsonObjectId> OBJECT_ID_CONVERTER = 
        (value, writer) -> {
            writer.writeStartObject();
            writer.writeName("$oid");
            writer.writeString(value.getValue().toHexString());
            writer.writeEndObject();
        };
    
    /**
     * A converter that writes DateTime values in strict JSON format.
     */
    public static final Converter<BsonDateTime> DATE_TIME_CONVERTER = 
        (value, writer) -> {
            writer.writeStartObject();
            writer.writeName("$date");
            writer.writeNumber(Long.toString(value.getValue()));
            writer.writeEndObject();
        };
    
    /**
     * A converter that writes Binary values in strict JSON format.
     */
    public static final Converter<BsonBinary> BINARY_CONVERTER = 
        (value, writer) -> {
            writer.writeStartObject();
            writer.writeName("$binary");
            writer.writeStartObject();
            writer.writeName("base64");
            writer.writeString(Base64.getEncoder().encodeToString(value.getData()));
            writer.writeName("subType");
            writer.writeString(String.format("%02x", value.getType()));
            writer.writeEndObject();
            writer.writeEndObject();
        };
    
    /**
     * A converter that writes Decimal128 values in strict JSON format.
     */
    public static final Converter<BsonDecimal128> DECIMAL128_CONVERTER = 
        (value, writer) -> {
            writer.writeStartObject();
            writer.writeName("$numberDecimal");
            writer.writeString(value.getValue().toString());
            writer.writeEndObject();
        };
}

Usage Examples

Basic JSON Conversion

import org.bson.*;
import org.bson.json.*;

// Create a BSON document
BsonDocument document = new BsonDocument()
    .append("name", new BsonString("John Doe"))
    .append("age", new BsonInt32(30))
    .append("_id", new BsonObjectId(new ObjectId()))
    .append("created", new BsonDateTime(System.currentTimeMillis()));

// Convert to JSON with different modes
String strictJson = document.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.STRICT)
    .build());

String extendedJson = document.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.EXTENDED)
    .build());

String relaxedJson = document.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.RELAXED)
    .build());

// Parse JSON back to BSON
BsonDocument parsed = BsonDocument.parse(strictJson);

Custom JSON Formatting

import org.bson.json.*;
import java.time.format.DateTimeFormatter;

JsonWriterSettings customSettings = JsonWriterSettings.builder()
    .outputMode(JsonMode.EXTENDED)
    .indent(true)
    .indentCharacters("  ")
    .newLineCharacters("\n")
    .dateTimeFormatter(DateTimeFormatter.ISO_INSTANT)
    .build();

String formattedJson = document.toJson(customSettings);

Streaming JSON Processing

import org.bson.json.*;
import java.io.*;

// Write JSON using JsonWriter
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter, 
    JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build());

jsonWriter.writeStartDocument();
jsonWriter.writeString("name", "Alice");
jsonWriter.writeInt32("age", 25);
jsonWriter.writeStartArray("hobbies");
jsonWriter.writeString("reading");
jsonWriter.writeString("coding");
jsonWriter.writeEndArray();
jsonWriter.writeEndDocument();
jsonWriter.close();

String json = stringWriter.toString();

// Read JSON using JsonReader
JsonReader jsonReader = new JsonReader(json);
jsonReader.readStartDocument();
while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
    String fieldName = jsonReader.readName();
    switch (jsonReader.getCurrentBsonType()) {
        case STRING:
            String stringValue = jsonReader.readString();
            break;
        case INT32:
            int intValue = jsonReader.readInt32();
            break;
        case ARRAY:
            jsonReader.readStartArray();
            while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
                String arrayItem = jsonReader.readString();
            }
            jsonReader.readEndArray();
            break;
    }
}
jsonReader.readEndDocument();
jsonReader.close();

Custom Type Converters

import org.bson.json.*;

// Custom converter for ObjectId that writes just the hex string
Converter<BsonObjectId> simpleObjectIdConverter = (value, writer) -> {
    writer.writeString(value.getValue().toHexString());
};

// Custom converter for DateTime that uses ISO format
Converter<BsonDateTime> isoDateConverter = (value, writer) -> {
    Instant instant = Instant.ofEpochMilli(value.getValue());
    writer.writeString(instant.toString());
};

JsonWriterSettings customConverterSettings = JsonWriterSettings.builder()
    .outputMode(JsonMode.EXTENDED)
    .objectIdConverter(simpleObjectIdConverter)
    .dateTimeConverter(isoDateConverter)
    .build();

String customJson = document.toJson(customConverterSettings);

Reading Large JSON Documents

import org.bson.json.*;
import java.io.*;

// Process large JSON documents with streaming
try (FileReader fileReader = new FileReader("large-document.json");
     JsonReader jsonReader = new JsonReader(fileReader)) {
    
    jsonReader.readStartDocument();
    while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
        String fieldName = jsonReader.readName();
        
        if (fieldName.equals("items")) {
            jsonReader.readStartArray();
            while (jsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) {
                // Process each item without loading entire array into memory
                jsonReader.readStartDocument();
                // ... read item fields
                jsonReader.readEndDocument();
            }
            jsonReader.readEndArray();
        } else {
            jsonReader.skipValue(); // Skip unknown fields
        }
    }
    jsonReader.readEndDocument();
}

Working with Different JSON Modes

BsonDocument doc = new BsonDocument()
    .append("_id", new BsonObjectId(new ObjectId()))
    .append("date", new BsonDateTime(System.currentTimeMillis()))
    .append("decimal", new BsonDecimal128(new Decimal128("123.45")))
    .append("binary", new BsonBinary(BsonBinarySubType.GENERIC, "Hello".getBytes()));

// Strict JSON (RFC compliant)
String strict = doc.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.STRICT).build());
// {"_id": {"$oid": "..."}, "date": {"$date": 1234567890}, ...}

// Extended JSON (MongoDB extended format)
String extended = doc.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.EXTENDED).build());
// {"_id": {"$oid": "..."}, "date": {"$date": "2023-..."}, ...}

// Relaxed JSON (more readable, some type info lost)
String relaxed = doc.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.RELAXED).build());
// {"_id": {"$oid": "..."}, "date": "2023-...", "decimal": 123.45, ...}

// Shell JSON (MongoDB shell compatible)
String shell = doc.toJson(JsonWriterSettings.builder()
    .outputMode(JsonMode.SHELL).build());
// {_id: ObjectId("..."), date: ISODate("..."), ...}

Install with Tessl CLI

npx tessl i tessl/maven-org-mongodb--bson

docs

codecs.md

core-types.md

index.md

io.md

json.md

legacy-api.md

types.md

tile.json