您是否知道Java库有助于将com.mongodb.DBObject
序列化/反序列化为BSON
二进制文件,反之亦然?
答案 0 :(得分:2)
这很简单,您可以使用以下帮助方法:
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);
}
答案 1 :(得分:1)
当您需要二进制BSON,即BSON格式的字节数组时,您可以使用以下对:
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();
}