簡體   English   中英

有沒有更好的辦法直接把一個Rust的BSON文檔轉成JSON?

[英]Is there a better way to directly convert a Rust BSON document to JSON?

思路是從 Mongo 獲取 cursor 並將結果集序列化為字符串中的 JSON。 我有工作代碼:

extern crate bson;
extern crate mongodb;

use mongodb::db::ThreadedDatabase;
use mongodb::{Client, ThreadedClient};

extern crate serde;
extern crate serde_json;

fn main() {
    let client =
        Client::connect("localhost", 27017).expect("Failed to initialize standalone client.");

    let coll = client.db("foo").collection("bar");

    let cursor = coll.find(None, None).ok().expect("Failed to execute find.");

    let docs: Vec<_> = cursor.map(|doc| doc.unwrap()).collect();

    let serialized = serde_json::to_string(&docs).unwrap();

    println!("{}", serialized);
}

有一個更好的方法嗎? 如果沒有,我將關閉此線程。

serde-transcode就是為這種情況而設計的。 它的作用是直接在serde格式之間進行轉換。 它是如何工作的,它接受一個Deserializer和一個Serializer ,然后直接為每個反序列化的項目調用相應的序列化 function 。 從概念上講,這有點類似於使用serde_json::Value作為中間格式,但它可能包含一些額外的類型信息(如果在輸入格式中可用)。

不幸的是, bson crate 沒有公開bson::de::raw::Deserializerbson::ser::raw::Serializer ,所以目前這是不可能的。 如果您查看文檔, DeserializerSerializer實際上指的是處理與Bson枚舉之間的轉換的不同結構。

如果bson::de::raw::Deserializer是公開的,那么此代碼將具有預期的效果。 希望這對任何有類似問題的人(或任何想要這個足以在他們的存儲庫上提出問題的人)有所幫助。

let mut buffer = Vec::new();

// Manually add array separators because the proper way requires going through
// DeserializeSeed and that is a whole other topic.
buffer.push(b'[');

while cursor.advance().await? {
    let bytes = cursor.current().as_bytes();

    // Create deserializer and serializer
    let deserializer = bson::de::raw::Deserializer::new(bytes, false);
    let serializer = serde_json::Serializer::new(&mut buffer);
    
    // Transcode between formats
    serde_transcode::transcode(deserializer, serializer).unwrap();

    // Manually add array separator
    buffer.push(b',');
}

// Remove trailing comma and add closing bracket
if buffer.len() > 1 {
    buffer.pop();
}
buffer.push(']');

// Do something with the result
println!("{}", String::from_utf8(buffer).unwrap())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM