Cereal JSON output misses closing curly brace
Asked Answered
F

1

6

I am using Cereal C++ v1.1.1 and similar to the example given in the documentation I am trying the following:

#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!
}

I expect to have the following:

{
  "x":12
}

but the closing curly brace is missing. Any idea what is missing in the code?

Update:

adding archive.finishNode() seems to solve the problem. But I would say that it's not the solution. According to the operator() documentation, calling the operator serializes the input parameters, why should I add the finishNode extra?

Fix answered 12/5, 2015 at 14:42 Comment(0)
C
14

I was having the same problem, and found the solution in a comment on an issue filed on Cereal's 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.

Cannoneer answered 15/5, 2015 at 21:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.