I’m using the C++ cereal
library to handle JSON serialization/deserialization in my Android application. I saw that cereal
added support for the std::optional
type. So after targeting C++17 in my CMakeLists
, I wrote a simple test case like this:
#include <string>
#include "cereal/types/optional.hpp"
struct SimpleObject {
int present;
std::optional<int> nullable;
template<class Archive>
void serialize(Archive &archive) {
archive(present, nullable);
}
};
int main() {
string myJson = "{ \"present\": 1, \"nullable\": null }";
stringstream is(myJson);
SimpleObject simpleObject;
{
cereal::JSONInputArchive archive(is);
simpleObject.serialize(archive);
}
return 0;
}
But my app is crashing with the following error: Abort message: 'terminating with uncaught exception of type cereal::RapidJSONException: rapidjson internal assertion failure: IsObject()'
.
What am I doing wrong? Shouldn’t it work out of the box like I did?
Or is cereal
expecting a JSON with another form?
I tried specifying a JSON string with only present
being present and no other field, but then I’m getting this error: Abort message: 'terminating with uncaught exception of type cereal::Exception: No more objects in input'
.
I also tried assigning a default std::nullopt
value without success.
What’s weird is both cases should be valid JSON.