2015-05-12 15 views
3

我使用Cereal C++ v1.1.1和類似的文件中給出的example我嘗試以下操作:穀物JSON輸出遺漏右大括號

#include <sstream> 
#include <iostream> 
#include <cereal/archives/json.hpp> 

int main() { 
    std::ostringstream os; 
    cereal::JSONOutputArchive archive(os); 
    int x = 12; 
    archive(CEREAL_NVP(x)); 
    std::cout << os.str(); // JUST FOR DEMONSTRATION! 
} 

我期望有以下幾點:

{ 
    "x":12 
} 

但最後的大括號缺失。任何想法在代碼中缺少什麼?

更新:

加入archive.finishNode()似乎解決了問題。但我會說這不是解決方案。根據operator()文檔,調用操作員序列化輸入參數,爲什麼我應該添加額外的finishNode

回答

8

我有同樣的問題,並發現了穀物的GitHub上提交關於某個問題的評論的解決方案:https://github.com/USCiLab/cereal/issues/101

的文檔狀態「檔案都設計在一個RAII 的方式來使用,並且保證只在 銷燬時刷新其內容......「(http://uscilab.github.io/cereal/quickstart.html)。

您的問題是,您正試圖在存檔被銷燬之前打印 stringstream的內容。在這一點上, 歸檔不知道您是否想在未來寫入更多的數據到它,因此它避免了流出大括號。 需要確保在 打印出字符串流之前調用了存檔的析構函數。

試試這個:

int main() 
{ 
    std::stringstream ss; 
    { 
    cereal::JSONOutputArchive archive(ss); 
    SomeData myData; 
    archive(myData); 
    } 
    std::cout << ss.str() << std::endl; 

    return 0; 
} 

請參閱文檔以獲取更多信息。

+0

幹得好!謝謝 :) –