cereal icon indicating copy to clipboard operation
cereal copied to clipboard

Added JSONInputArchive constructor from an already parsed rapidjson::Document

Open dev-plvlml opened this issue 4 years ago • 0 comments

Hi, And thanks for a great library!

I've got the following problem.

std::string jsonStr;
rapidjson::Document doc;
doc.Parse(jsonStr.data());

if (doc["type"].GetString() == "foo") {  // "type" field can't be renamed
    Foo foo{};
    {
        std::istringstream input{jsonStr};
        cereal::JSONInputArchive archive{input};  // creates a new Document and parses the string again!
        serialize(archive, foo);
    }
    applyStaticallyTypedCallback(foo);

} else if (doc["type"].GetString() == "bar") {
    Bar bar{};
    // etc.
}

I'm aware that some similar (de)serializing could be done with the built-in Polymorphic Types feature, but it uses its own internal fields like "polymorphic_name" and "polymorphic_id", whose names are hardcoded, and the code around them seems not so easy to intervene and customize.

I propose to allow constructing JSONInputArchive via move-from an already parsed rapidjson::Document to fix at least the performance issues of this case:

rapidjson::Document doc;

if (doc["type"].GetString() == "foo") {
    Foo foo{};
    {
        cereal::JSONInputArchive archive{std::move(doc)};  // no more parsing!
        serialize(archive, foo);
    }
    applyStaticallyTypedCallback(foo);
}

dev-plvlml avatar Aug 02 '20 17:08 dev-plvlml