如何在Rust中将mongodb::bson::Document转为Vec<u8>适配C#解析?
解决Rust到C#的BSON对象传输问题
既然你已经搞定了C#端BSON字节数组到Rust mongodb::bson::Document 的解析,反向操作其实非常直接——用Rust的mongodb::bson库自带的序列化方法就能生成和C#端兼容的标准BSON字节流。
核心实现方式
Rust的mongodb::bson库提供了两种实用方法,把Document转换成Vec<u8>:
1. 直接生成字节数组(推荐)
用bson::to_vec函数一步完成序列化,生成的字节数组和C# MongoDB.Bson.ToBson()输出格式完全一致:
use mongodb::bson::{doc, Document, to_vec}; // 示例:创建一个Rust Document对象 let sample_doc = doc! { "user_id": 12345, "username": "Fabian", "preferences": { "theme": "dark", "notifications": true } }; // 转换为BSON格式的字节数组 let bson_bytes = to_vec(&sample_doc) .expect("Failed to serialize Document to BSON bytes");
2. 手动写入流(适合自定义场景)
如果需要将BSON直接写入特定流(比如WebSocket发送流),可以用bson::to_writer方法:
use std::io::Cursor; use mongodb::bson::{doc, Document, to_writer}; let mut buffer = Cursor::new(Vec::new()); let sample_doc = doc! { "message": "Hello from Rust!" }; // 将Document写入缓冲区 to_writer(&mut buffer, &sample_doc) .expect("Failed to write Document to buffer"); // 提取最终的字节数组 let bson_bytes = buffer.into_inner();
C#端接收解析验证
把Rust生成的bson_bytes通过WebSocket发送到C#端后,直接用BsonDocument.ReadFrom()就能正常解析:
// 假设receivedBytes是从WebSocket接收到的字节数组 using var stream = new MemoryStream(receivedBytes); var doc = BsonDocument.ReadFrom(stream);
这个流程和你之前C#到Rust的解析完全对称,因为两边都遵循标准BSON规范,且用的都是MongoDB官方维护的BSON库,兼容性完全有保障。
内容的提问来源于stack exchange,提问作者Fabian Schempp
相关产品推荐
相关产品推荐

