Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cereal JSON output misses closing curly brace

Tags:

c++

json

cereal

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?

like image 801
Yan Foto Avatar asked May 12 '15 14:05

Yan Foto


1 Answers

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.

like image 140
Samusaaron3 Avatar answered Nov 01 '22 06:11

Samusaaron3