我正在使用 Cereal C++ v1.1.1类似于 example文档中给出我正在尝试以下操作:
#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
?
最佳答案
我遇到了同样的问题,并在 Cereal 的 GitHub 上提交的问题的评论中找到了解决方案:https://github.com/USCiLab/cereal/issues/101
The documentation states "Archives are designed to be used in an RAII manner and are guaranteed to flush their contents only on destruction..." (http://uscilab.github.io/cereal/quickstart.html).
Your problem is that you are trying to print the contents of the stringstream before the archive has been destroyed. At this point, the archive has no idea whether you will want to write more data to it in the future, so it refrains from streaming out the closing brace. You need to make sure the archive's destructor has been called before printing out the stringstream.
Try this:
int main() { std::stringstream ss; { cereal::JSONOutputArchive archive( ss ); SomeData myData; archive( myData ); } std::cout << ss.str() << std::endl; return 0; }
Please see the documentation for more information.
关于c++ - Cereal JSON 输出缺少右大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30194212/