Class BsonSerializer

All Implemented Interfaces:
Function<Object,byte[]>, ThrowingFunction<Object,byte[]>, BsonMetaProvider, ArrayRecordWritable, RecordWritable
Direct Known Subclasses:
BsonSerializer.Base64, BsonSerializer.SpacedHex

Serializes POJO models to BSON (Binary JSON).
Media types:
Handles Accept types: application/bson

Produces Content-Type types: application/bson

Description

Java-to-BSON type mapping:

  • Maps and beans → BSON document (type 0x03)
  • Collections and arrays → BSON array (type 0x04, document with numeric string keys)
  • String / Enum → BSON string (type 0x02)
  • Boolean → BSON boolean (type 0x08)
  • int / short / byte → BSON int32 (type 0x10)
  • long → BSON int64 (type 0x12)
  • float / double → BSON double (type 0x01)
  • Date / Calendar / Instant → BSON datetime (type 0x09) when writeDatesAsDatetime=true; otherwise ISO 8601 string
  • Duration → ISO 8601 duration string
  • byte[] → BSON binary (type 0x05, subtype 0x00)
  • BigDecimal / BigInteger → BSON decimal128 (type 0x13)
  • null → BSON null (type 0x0A)
  • All other types → fallback to toString() as string
Notes:
  • This class is thread safe and reusable.
Limitations:
  • 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 (0x07) is not generated; parsing returns 24-character hex strings.
  • Deprecated types (Undefined, DBPointer, Symbol, JS with Scope) are skipped during parsing.
  • MongoDB-internal types (JavaScript, Timestamp, MinKey, MaxKey) are not supported.
  • BigDecimal / BigInteger values outside the Decimal128 range (max 34 significant digits, exponent -6176..6111) cannot be represented and throw a SerializeException with a clear message.
  • BSON datetime (0x09) is millisecond-resolution, so sub-millisecond (nanosecond) precision of Instant/OffsetDateTime/ZonedDateTime is truncated when writeDatesAsDatetime=true. Use writeDatesAsDatetime=false for lossless ISO-8601 string output.
  • Local java.time types (LocalDate, LocalDateTime, LocalTime, Year, etc.) have no instant, so they are always written as ISO-8601 strings even when writeDatesAsDatetime=true.
  • BSON is binary; SpacedHex and Base64 subclasses provide text-encodable output.
Example:

// Serialize a POJO to BSON byte[] bson = BsonSerializer.DEFAULT.write(someObject); // Create a serializer that writes dates as ISO 8601 strings instead of BSON datetime BsonSerializer s = BsonSerializer.create().writeDatesAsDatetime(false).build(); // Or use the marshaller for convenience bson = Bson.of(someObject);

See Also: