Package org.apache.juneau.marshall.bson
Class BsonSerializer
- All Implemented Interfaces:
Function<Object,,byte[]> ThrowingFunction<Object,,byte[]> BsonMetaProvider,ArrayRecordWritable,RecordWritable
- Direct Known Subclasses:
BsonSerializer.Base64,BsonSerializer.SpacedHex
public class BsonSerializer
extends OutputStreamSerializer
implements BsonMetaProvider, RecordWritable, ArrayRecordWritable
Serializes POJO models to BSON (Binary JSON).
Accept types: application/bson
Media types:
Handles
Produces
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) whenwriteDatesAsDatetime=true; otherwise ISO 8601 stringDuration→ ISO 8601 duration stringbyte[]→ 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/BigIntegervalues outside the Decimal128 range (max 34 significant digits, exponent -6176..6111) cannot be represented and throw aSerializeExceptionwith a clear message.- BSON datetime (0x09) is millisecond-resolution, so sub-millisecond (nanosecond) precision of
Instant/OffsetDateTime/ZonedDateTimeis truncated whenwriteDatesAsDatetime=true. UsewriteDatesAsDatetime=falsefor lossless ISO-8601 string output. - Local
java.timetypes (LocalDate,LocalDateTime,LocalTime,Year, etc.) have no instant, so they are always written as ISO-8601 strings even whenwriteDatesAsDatetime=true. - BSON is binary;
SpacedHex andBase64 subclasses provide text-encodable output.
Example:
See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classDefault serializer, BASE64 string output.static classBuilder class.static classDefault serializer, spaced-hex string output.Nested classes/interfaces inherited from class org.apache.juneau.marshall.serializer.OutputStreamSerializer
OutputStreamSerializer.DefaultBuilderNested classes/interfaces inherited from class org.apache.juneau.marshall.serializer.Serializer
Serializer.Null -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final booleanstatic final BsonSerializerDefault serializer, all default settings.static final BsonSerializerDefault serializer, BASE64 string output.static final BsonSerializerDefault serializer, spaced-hex string output.protected final Stringprotected final booleanFields inherited from class org.apache.juneau.marshall.serializer.Serializer
accept, addBeanTypes, addRootType, keepNullProperties, listener, nonDefault, produces, sortCollections, sortMaps, trimEmptyCollections, trimEmptyMaps, trimStringsFields inherited from class org.apache.juneau.marshall.MarshallingContextable
marshallingContextFields inherited from class org.apache.juneau.marshall.Context
CONTEXT_APPLY_FILTER -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptioncopy()Creates a builder from this context object.static BsonSerializer.Buildercreate()Creates a new builder for this object.Create a session builder based on the properties defined on this context.Returns the language-specific metadata on the specified bean property.getBsonClassMeta(ClassMeta<?> cm) Returns the language-specific metadata on the specified class.Returns a session to use for this context.protected final booleanAdd"_type" properties when needed.booleanThe BSON array-record writer is buffered/RecordAdapter-backed, not O(1) streaming.booleanThe BSON record writer is buffered/RecordAdapter-backed, not O(1) streaming.Returns the properties on this bean as a map for debugging.writeArrayRecords(Object output) Convenience delegator for the buffered array-elementRecordWriterusing default session arguments.writeRecords(Object output) Convenience delegator for the whole-valueRecordWriterusing default session arguments.Methods inherited from class org.apache.juneau.marshall.serializer.OutputStreamSerializer
applyThrows, getBinaryFormat, isWriterSerializer, writeMethods inherited from class org.apache.juneau.marshall.serializer.Serializer
createSerializerBuilder, doWrite, forEachAcceptMediaType, getListener, getMediaTypeRanges, getPrimaryMediaType, getResponseContentType, getResponseHeaders, getUriContext, getUriRelativity, getUriResolution, isAddRootType, isKeepNullProperties, isNonDefault, isSortCollections, isSortMaps, isTrimEmptyCollections, isTrimEmptyMaps, isTrimStrings, write, writeToStringMethods inherited from class org.apache.juneau.marshall.MarshallingTraverseContext
getDetectRecursions, getIgnoreRecursions, getInitialDepth, getMaxDepth, isDetectRecursions, isIgnoreRecursions, shouldDetectRecursionsMethods inherited from class org.apache.juneau.marshall.MarshallingContextable
getDurationFormat, getMarshallingContext, getPeriodFormatMethods inherited from class org.apache.juneau.marshall.Context
createBuilder, getAnnotationProvider, init, isDebug, toStringMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.apache.juneau.marshall.stream.ArrayRecordWritable
writeArrayRecordsMethods inherited from interface org.apache.juneau.commons.function.ThrowingFunction
apply
-
Field Details
-
DEFAULT
Default serializer, all default settings. -
DEFAULT_SPACED_HEX
Default serializer, spaced-hex string output. -
DEFAULT_BASE64
Default serializer, BASE64 string output. -
addBeanTypesBson
-
nullKeyString
-
writeDatesAsDatetime
-
-
Constructor Details
-
BsonSerializer
Constructor.- Parameters:
builder- The builder for this object.
-
-
Method Details
-
create
Creates a new builder for this object.- Returns:
- A new builder.
-
copy
Description copied from class:ContextCreates a builder from this context object.Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
- Overrides:
copyin classSerializer- Returns:
- A new Builder object.
-
createSession
Description copied from class:ContextCreate a session builder based on the properties defined on this context.Use this method for creating sessions where you want to override basic settings. Otherwise, use
Context.getSession()directly.- Overrides:
createSessionin classOutputStreamSerializer- Returns:
- A new session builder.
-
getBsonBeanPropertyMeta
Description copied from interface:BsonMetaProviderReturns the language-specific metadata on the specified bean property.- Specified by:
getBsonBeanPropertyMetain interfaceBsonMetaProvider- Parameters:
bpm- The bean property to return the metadata on.- Returns:
- The metadata.
-
getBsonClassMeta
Description copied from interface:BsonMetaProviderReturns the language-specific metadata on the specified class.- Specified by:
getBsonClassMetain interfaceBsonMetaProvider- Parameters:
cm- The class to return the metadata on.- Returns:
- The metadata.
-
getSession
Description copied from class:ContextReturns a session to use for this context.Note that subclasses may opt to return a reusable non-modifiable session.
- Overrides:
getSessionin classOutputStreamSerializer- Returns:
- A new session object.
-
isAddBeanTypes
Description copied from class:SerializerAdd"_type" properties when needed.- Overrides:
isAddBeanTypesin classSerializer- Returns:
true if"_type" properties added to beans if their type cannot be inferred through reflection.- See Also:
-
properties
Description copied from class:ContextReturns the properties on this bean as a map for debugging.- Overrides:
propertiesin classSerializer- Returns:
- The properties on this bean as a map for debugging.
-
writeRecords
Convenience delegator for the whole-valueRecordWriterusing default session arguments. The real implementation lives onBsonSerializerSession.writeRecords(Object).- Specified by:
writeRecordsin interfaceRecordWritable- Parameters:
output- The output.- Returns:
- A new
RecordWriter. - Throws:
IOException- If a problem occurred opening the underlying output.
-
writeArrayRecords
Convenience delegator for the buffered array-elementRecordWriterusing default session arguments. BSON's wire format requires the entire document byte-length up front (length prefix at every nesting level), so streaming without buffering is not possible. The real implementation lives onBsonSerializerSession.writeArrayRecords(Object).- Specified by:
writeArrayRecordsin interfaceArrayRecordWritable- Parameters:
output- The output.- Returns:
- A buffered
RecordWriter. - Throws:
IOException- If a problem occurred opening the underlying output.
-
isRecordStreaming
The BSON record writer is buffered/RecordAdapter-backed, not O(1) streaming.- Specified by:
isRecordStreamingin interfaceRecordWritable- Returns:
- Always
false .
-
isArrayRecordStreaming
The BSON array-record writer is buffered/RecordAdapter-backed, not O(1) streaming.- Specified by:
isArrayRecordStreamingin interfaceArrayRecordWritable- Returns:
- Always
false .
-