Last active
February 15, 2023 19:01
-
-
Save Koboo/ebd7c6802101e1a941ef31baca04113d to your computer and use it in GitHub Desktop.
Just a static utility class to convert BSON Documents to byte-array and vice versa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.bson.BsonBinaryReader; | |
import org.bson.BsonBinaryWriter; | |
import org.bson.Document; | |
import org.bson.codecs.Codec; | |
import org.bson.codecs.DecoderContext; | |
import org.bson.codecs.DocumentCodec; | |
import org.bson.codecs.EncoderContext; | |
import org.bson.io.BasicOutputBuffer; | |
import java.nio.ByteBuffer; | |
public class BsonToBinary { | |
private static final Codec<Document> DOCUMENT_CODEC = new DocumentCodec(); | |
public static byte[] toBytes(Document document) { | |
BasicOutputBuffer buffer = new BasicOutputBuffer(); | |
BsonBinaryWriter writer = new BsonBinaryWriter(buffer); | |
DOCUMENT_CODEC.encode(writer, document, EncoderContext.builder().isEncodingCollectibleDocument(true).build()); | |
buffer.close(); | |
return buffer.toByteArray(); | |
} | |
public static Document toDocument(byte[] bytes) { | |
BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(bytes)); | |
Document document = DOCUMENT_CODEC.decode(reader, DecoderContext.builder().build()); | |
reader.close(); | |
return document; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment