谷物 - 无法反序列化 json 字符串 - 未处理的异常

Cereal - unable to deserialize a json string - unhandled exception

这是我的 json 字符串

{
    "connectionString" : "MyConnectionString",
    "value" :"MyVal"
}

这是我的class

        struct Settings
        {
            std::string connectionString;
            std::string value;

            template<class Archive>
            void serialize(Archive& ar)
            {
                    ar(CEREAL_NVP(connectionString),
                    CEREAL_NVP(value)
                );
            }
        };

这就是我正在做的事情:

            std::ifstream ifs("Settings.json");
            std::string content((std::istreambuf_iterator<char>(ifs)),(std::istreambuf_iterator<char>())); // Yes this is valid - The content gets populated
            
            Settings settings;
            {
                cereal::JSONInputArchive archive_in(ifs);
                archive_in(settings); //<<-----Exception here - Unhandled exception
            }

只有当我的 json 字符串是这个时(即,如果所有 json 字符串都是另一个键的对象,上述解决方案才有效。

{
    "SomeThing" :{
                "connectionString" : "MyConnectionString",
                "value" :"MyVal"
       }
}

我的问题是如何使实际的 json 字符串起作用(不将其包装在对象中)?我目前在 json 文件

中有这个
{
    "connectionString" : "MyConnectionString",
    "value" :"MyVal"
}

我想知道将其反序列化为对象的最佳方法?

期望外部对象默认放置在那里的代码JSON“序言”和“结尾”行为:

https://github.com/USCiLab/cereal/blob/10d9a29c225fe9a843d043bfe9f13c5f958844dc/include/cereal/archives/json.hpp#L837

来自documentation

These functions are given a reference to the active archive and a constant reference to the type being serialized. Careful specialization of prologue and epilogue allows for archives to exercise special behaviors without having to re-implement serialization functions for types. This lets us make the type support fairly generic. For example, cereal::XMLOutputArchive (<cereal/archives/xml.hpp>) makes use of these functions to start and finish nodes in its in-memory tree.

如果您在代码中为您的类型添加一个不执行任何操作的重载:

void epilogue(cereal::JSONInputArchive&, const Settings&) { }
void prologue(cereal::JSONInputArchive&, const Settings&) { }

它不会尝试解析外部对象