0

Hi anyone knows of a Java library to help serialize/deserialize a com.mongodb.DBObject into a BSON binary and vise-versa?

1

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.