来自 RawBsonDocument.getByteBuffer().array() in org.Bson 的字节数组中的尾随零

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

我正在尝试将 org.Json JSON 对象编码为 BSON 格式 byte[]。 但是,我注意到生成的 byte[] 有尾随零。虽然这些零在将 byte[] 再次反序列化为 JSON 时不会造成问题,但它们确实占用了很多 space。 我的代码如下:

#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();

简单地从所有尾随零中修剪 byte[] 不是一种选择,因为 byte[] 很可能在末尾有有效的零,而序列化没有添加这些零。

编辑 1

我用下面的代码解决了这个问题:

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

我觉得很难,一定是一个更优雅的答案

我在类似的class中也遇到过这个问题,并通过截断内部缓冲区的副本解决了这个问题。

由于getByteBuffer returns 文档对象所在的内部缓冲区,结尾未使用的空间用零填充,这导致了问题。

这是我的解决方案:

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

其中 writeBuffer 是一个 BasicOutputBuffer 实例,它实现了 org.bson 的 OutputBuffer 接口。所以这也适用于您的情况。