Bson is an implementation of the BSON specification complete with BSON serialisation and deserialisation.
Note that BSON is an extention of JSON, and JSON can only represent a subset of the types supported by BSON.
Bson was created to support the development of the Fantom Factory MongoDB driver.
Install Bson
with the Fantom Pod Manager ( FPM ):
C:\> fpm install afBson
Or install Bson
with fanr:
C:\> fanr install -r http://eggbox.fantomfactory.org/fanr/ afBson
To use in a Fantom project, add a dependency to build.fan
:
depends = ["sys 1.0", ..., "afBson 2.0"]
Full API & fandocs are available on the Eggbox - the Fantom Pod Repository.
1). Create a text file called Example.fan
:
using afBson
class Example {
Void main() {
docIn := [
"_id" : ObjectId(),
"name" : "Dave",
"age" : 42
]
// serialise BSON to a Buf
buf := BsonIO().writeDoc(documentIn)
// deserialise BSON from a stream
docOut := BsonIO().readDoc(buf.flip.in)
echo(docOut)
}
}
2). Run Example.fan
as a Fantom script from the command line:
C:\> fan Example.fan
[_id:53503531a8000b8b44000001, name:Dave, age:42]
The BsonIO class (de)serialises BSON documents to and from Fantom using the following mapping:
BSON <-> Fantom
-------------------------------
ARRAY <-> sys::List
BINARY <-> afBson::Binary
BOOLEAN <-> sys::Bool
CODE --> sys::Str (read only)
DATE <-> sys::DateTime
DOCUMENT <-> sys::Map
DOUBLE <-> sys::Float
INTEGER_32 --> sys::Int (read only)
INTEGER_64 <-> sys::Int
MAX_KEY <-> afBson::MaxKey
MIN_KEY <-> afBson::MinKey
NULL <-> null
OBJECT_ID <-> afBson::ObjectId
REGEX <-> sys::Regex
STRING <-> sys::Str
TIMESTAMP <-> afBson::Timestamp
Bson
takes care of all the tricky Endian
ness. All BSON objects may be serialised to and from strings using Fantom's standard serialisation techniques.
Deprecated BSON constructs (CODE_W_SCOPE
, DB_POINTER
, SYMBOL
, and UNDEFINED
) are ignored and have no Fantom representation.
INTEGER_32
values are read as Fantom (64-bit)Ints
CODE
objects are read as FantomStrs
REGEX
flags are read and converted into embedded character flags (e.g.,/myregex/im
is converted to/(?im)myregex/
)
If these objects are subsequently written back (to MongoDB), be aware that their backing storage type will change to represent their new Fantom type. This is only noteworthy if other, non Fantom, drivers are reading / writing values to / from the database.
See Java's Pattern Class for a list of supported regex flags (dimsuxU
).
The Fantom Factoy BSON library was inspired by fantomongo
by Liam Staskawicz.