quarks
quarks

Reputation: 35276

com.mongodb.DBObject / BSON serializer for java

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

Upvotes: 0

Views: 3519

Answers (2)

Alex InTechno
Alex InTechno

Reputation: 1261

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

Upvotes: 1

meaclum
meaclum

Reputation: 96

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

Upvotes: 2

Related Questions