Skip to main content

BSON

Juneau supports converting arbitrary POJOs to and from BSON (Binary JSON) using native serializers and parsers. BSON is the binary serialization format used by MongoDB, extending JSON with typed integers (int32/int64), native datetime, decimal128, and binary data. It uses little-endian byte order and length-prefixed documents.

The BsonSerializer converts POJOs directly to BSON format, and the BsonParser creates POJOs directly from BSON.

BSON support is included in juneau-marshall.

Maven
<dependency>
<groupId>org.apache.juneau</groupId>
<artifactId>juneau-marshall</artifactId>
<version>${juneau.version}</version>
</dependency>

Quick Start​

// A simple bean
public class Person {
public String name;
public int age;
public Person() {}
public Person(String name, int age) { this.name = name; this.age = age; }
}

// Serialize a bean to BSON
Person alice = new Person("Alice", 30);
byte[] bson = Bson.of(alice);

// Parse BSON into a bean
Person parsed = Bson.to(bson, Person.class);

Parsing​

// Parse BSON into a bean
Person p = Bson.to(bson, Person.class);

// Parse into a map
JsonMap map = Bson.to(bson, JsonMap.class);

// Parse into a typed map
Map<String, Object> m = Bson.to(bson, Map.class, String.class, Object.class);

// Parse a list (root must be document; use wrapped {"value": [...]} for standalone arrays)
List<Person> people = Bson.to(bson, List.class, Person.class);

Serialization​

// Use the default serializer
byte[] bson = BsonSerializer.DEFAULT.write(someObject);

// Use the marshaller for convenience
byte[] bson = Bson.of(someObject);

// Custom serializer: write dates as ISO 8601 strings instead of BSON datetime
BsonSerializer s = BsonSerializer.create().writeDatesAsDatetime(false).build();
byte[] bson = s.write(someObject);

Java-to-BSON Type Mapping​

Java TypeBSON TypeNotes
Bean, MapDocument (0x03)Nested structures
Collection, arrayArray (0x04)Document with "0", "1", ... keys
String, EnumString (0x02)
int, short, byteInt32 (0x10)4 bytes little-endian
longInt64 (0x12)8 bytes little-endian
float, doubleDouble (0x01)IEEE 754
Date, Calendar, InstantDatetime (0x09)When writeDatesAsDatetime=true
DurationStringISO 8601 duration
byte[]Binary (0x05)Subtype 0x00
BigDecimal, BigIntegerDecimal128 (0x13)IEEE 754-2008
nullNull (0x0A)

Local java.time types with no instant (LocalDate, LocalDateTime, LocalTime, Year, etc.) are always written as ISO 8601 strings. BSON datetime has millisecond resolution, so sub-millisecond precision of Instant, OffsetDateTime and ZonedDateTime is truncated when writeDatesAsDatetime is true; use writeDatesAsDatetime(false) for lossless ISO 8601 output. BigDecimal / BigInteger values outside the Decimal128 range (34 significant digits, exponent -6176..6111) cannot be represented and fail with a SerializeException.

Pre-configured instances​

InstanceDescription
BsonSerializer.DEFAULT / BsonParser.DEFAULTDefault settings; raw BSON bytes.
BsonSerializer.DEFAULT_SPACED_HEX / BsonParser.DEFAULT_SPACED_HEXbinaryFormat(SPACED_HEX).
BsonSerializer.DEFAULT_BASE64 / BsonParser.DEFAULT_BASE64binaryFormat(BASE64).

The binary format setting only affects the stream-to-string conveniences (such as writeToString); the serializer always emits native BSON bytes from write(...).

Serializer settings​

Configured through BsonSerializer.create() (see BsonSerializer.Builder).

Builder methodDefaultDescription
addBeanTypesBson(boolean)falseAdd _type properties to beans whose type cannot be inferred through reflection.
writeDatesAsDatetime(boolean)trueWrite Date / Calendar / Instant as BSON datetime (0x09); when false, write ISO 8601 strings.
nullKeyString(String)"<NULL>"Field name used for null map keys (BSON field names cannot be null).
binaryFormat(BinaryFormat)NOT_SETText rendering (SPACED_HEX, HEX, BASE64, BASE64_URL) used by string conveniences.

The defaults can also be set with the BsonSerializer.addBeanTypesBson, BsonSerializer.nullKeyString and BsonSerializer.writeDatesAsDatetime environment settings.

Parser settings​

Configured through BsonParser.create() (see BsonParser.Builder).

Builder methodDefaultDescription
nullKeyString(String)"<NULL>"A field with this name is stored with a null key in the target map. Must match the serializer value.
trimStrings(boolean)falseTrim whitespace from parsed string values (inherited from Parser).
binaryFormat(BinaryFormat)NOT_SETBinary text-format hint (SPACED_HEX, HEX, BASE64, BASE64_URL); see BinaryFormat.
BsonSerializer s = BsonSerializer.create()
.writeDatesAsDatetime(false)
.nullKeyString("~null~")
.build();
BsonParser p = BsonParser.create().nullKeyString("~null~").build();

byte[] bson = s.write(someMap);
Map<?,?> m = p.read(bson, Map.class);

Media Types​

  • Produces: application/bson
  • Accepts: application/bson

REST Integration​

// BSON support is included via BasicUniversalConfig (there is no dedicated BSON-only config interface).
@Rest
public class MyResource extends RestServlet implements BasicUniversalConfig { ... }

// RestClient with BSON
RestClient client = RestClient.create().uri("http://localhost:8080").bson().build();
byte[] response = client.get("/api/data").bson().run().body();

Limitations​

  • Root must be a document: BSON requires a top-level document. Standalone scalars, collections, and arrays are wrapped as {value: x}.
  • Map keys must be strings: Non-string keys use toString(). Null keys use a configurable placeholder.
  • ObjectId is read-only: BSON ObjectId (0x07) is parsed as a 24-character hex string; Juneau does not generate ObjectIds.
  • Deprecated types skipped: Undefined, DBPointer, Symbol, JS with Scope are silently skipped during parsing.
  • MongoDB-internal types unsupported: JavaScript, Timestamp, MinKey, MaxKey are not supported.

Annotations​

@BsonConfig sets serializer/parser properties on a REST class or method (see Context Annotations). Attributes are strings:

AttributeDescription
addBeanTypesAdd _type properties to beans whose type can't be inferred through reflection (default false).
writeDatesAsDatetimeWrite Date/Calendar/Instant as the BSON datetime type (0x09); if false, write ISO-8601 strings.
maxLengthMaximum wire-declared length (bytes) for strings, binary payloads and document/array size prefixes when parsing; guards against malicious size prefixes.
rankOrdering relative to other config annotations.
@Rest
@BsonConfig(writeDatesAsDatetime="true", maxLength="1048576")
public class MyResource extends BasicRestServlet { ... }

@Bson is a class/method/field marker (its only attribute is description), and @BsonApply applies it to other classes/members via on()/onClass() (see Dynamically Applied Annotations).

See Also