Search code examples
javamongodbbytebsonorg.json

Trailing zeros in byte array from RawBsonDocument.getByteBuffer().array() in org.Bson


I am trying to encode an org.Json JSONObject into a BSON format byte[]. I have noticed, however, that the resulting byte[] has trailing zeros. While these zeros do not pose a problem when deserializing the byte[] to JSON again, they do however take up a lot of space. My code is the following:

#deserializing incoming message
RawBsonDocument bson = new RawBsonDocument((byte[])incomingBson);
json = new JSONObject(bson.toJson());

#serializing response to **bson format**
RawBsonDocument bsonDoc = RawBsonDocument.parse(json.toString());
responseBson = bsonDoc.getByteBuffer().array();

Simply trimming the byte[] from all trailing zeroes is not an option, since the byte[] can very well have valid zeros at the end, that where not added by the serialization.

Edit 1

I solved the issue with the following code:

RawBsonDocument bsonDoc = RawBsonDocument.parse(json.toString());
responseBson = Arrays.copyOfRange(bsonDoc.getByteBuffer().array(), 0, bsonDoc.getByteBuffer().limit());

I feel as tough the must be a more elegant answer


Solution

  • I also encountered this problem in a similar class and solved it by making a truncated copy of the internal buffer.

    Since getByteBuffer returns the internal buffer which the document object holds, the ending unused spaces are filled with zeros, which caused the problem.

    Here is my solution:

    return Arrays.copyOf(writeBuffer.getInternalBuffer(), writeBuffer.getSize());
    

    where writeBuffer is a BasicOutputBuffer instance which implements org.bson's OutputBuffer interface. So this should also work in your situation.