Hi anyone knows of a Java library to help serialize/deserialize a com.mongodb.DBObject into a BSON binary and vise-versa?
2 Answers
It's fairly simple, you can use the following helper methods:
public static byte[] encode(BSONObject bsonObject) {
BSONEncoder encoder = new BasicBSONEncoder();
return encoder.encode(bsonObject);
}
public static BSONObject readObject(InputStream is) throws IOException {
BasicBSONDecoder encoder = new BasicBSONDecoder();
return encoder.readObject(is);
}
public static BSONObject readObject(byte[] bsonObject) {
BasicBSONDecoder encoder = new BasicBSONDecoder();
return encoder.readObject(bsonObject);
}
Comments
When you need binary BSON, i.e., byte array in BSON format, you may use the following pair:
public byte[] DBObjectToBSON(DBObject dbObject) {
BasicBSONEncoder encoder = new BasicBSONEncoder();
return encoder.encode(dbObject);
}
public DBObject BSONToDBObject(byte[] bson) {
BasicBSONDecoder decoder = new BasicBSONDecoder();
JSONCallback callback = new JSONCallback();
decoder.decode(bson, callback);
return (DBObject) callback.get();
}
BasicBSONEncoder/Decoderhere: api.mongodb.org/java/current/index.html?org/bson/…)?