c++ - Cereal JSON 输出缺少右大括号

标签 c++ json cereal

我正在使用 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/

相关文章:

c++ - 使用 QueuedConnection 还是 QMutex 来使对象线程安全?

C++ Cereal 反序列化问题与大尺寸 vector

Javascript:JSON 请求仅在第一次有效

没有参数的 java.lang.RuntimeException : Failed to invoke public com. example.syncapp.MessageBase()

c++ - 函数如何修改C++中按值传递的参数?

c++ - Cereal 序列化和多态性

c++ - 这个 backward_warning.h #warning 来自哪里?

c++ - 静态字符数组的对齐保证

c++ - if 字符串验证循环的问题

python - 为什么这个 python 脚本不会输入到我设置的 MySQL 表中?