@Override
public int writeObject(OutputBuffer buf, BSONObject object) {
if (object instanceof JacksonDBObject) {
JacksonDBObject<?> jacksonDbObject = (JacksonDBObject<?>) object;
OutputBufferOutputStream stream = new OutputBufferOutputStream(buf);
BsonGenerator generator = new DBEncoderBsonGenerator(
JsonGenerator.Feature.collectDefaults(), stream);
try {
objectMapper.writerWithView(jacksonDbObject.getView())
.writeValue(generator, jacksonDbObject.getObject());
// The generator buffers everything so that it can write the
// number of bytes to the stream
generator.close();
} catch (JsonMappingException e) {
throw new MongoJsonMappingException(e);
} catch (IOException e) {
throw new MongoException("Error writing object out", e);
}