gpt4 book ai didi

c++ - 使用 Cereal 反序列化 JSON 字符串

转载 作者:搜寻专家 更新时间:2023-10-31 01:30:41 26 4
gpt4 key购买 nike

我是 Cereal 的新手,我很难理解如何反序列化 JSON 字符串。不幸的是,我的工作防火墙限制我访问 Google 网上论坛以在留言板上发帖。

我有一个类,我可以将其转换为 JSON 字符串,但我终究无法获取该字符串并重新创建该类。任何帮助将不胜感激,请保持温柔,我刚从学校毕业,这是我的第一份工作,我已经超出了我的能力范围。

这是我得到的错误:

在抛出“cereal::RapidJSONException”实例后调用终止 what():rapidjson 内部断言失败:IsObject()

下面是MyClass.hpp类:

#include <cstdio>
#include <iostream>
#include <string>
#include "../cereal/access.hpp"

class MyClass{
Public: //function declarations
template<class Archive> // public serialization (normal)
void serialize(Archive & ar)
{
ar(x, y, z);
}

private: // member variables
string x;
int y;
bool z;
};

下面是我的 Main.cpp:

#include <../cereal/types/unordered_map.hpp>
#include <../cereal/types/memory.hpp>
#include <../cereal/types/concepts/pair_associative_container.hpp>
#include <../cereal/archives/json.hpp>
#include <../cereal/types/vector.hpp>

#include <iostream>
#include <fstream>

#include "MyClass.hpp"

int main(){
// serialize (this part all works... i think)
{
// create a class object and give it some data
MyClass data("hello", 6, true);
// create a string stream object
std::stringstream os;
// assign the string stream object to the Output Archive
cereal::JSONOutputArchive archive_out(os);
//write data to the output archive
archive_out(CEREAL_NVP( data ));
// write the string stream buffer to a variable
string json_str = os.str();
}
// deserialize
{
// create a string stream object and pass it the string variable holding the JSON archive
std::stringstream is( json_str );
// pass the stream sting object into the input archive **** this is the line of code that generates the error
cereal::JSONInputArchive archive_in( is );
// create a new object of MyClass
MyClass data_new;
// use input archive to write data to my class
archive_in( data_new );
}
}

最佳答案

根据 Cereal 文件

Some archives in cereal can only safely finish flushing their contents upon their destruction. Make sure, especially for output serialization, that your archive is automatically destroyed when you are finished with it.

因此在序列化 block 之外调用 os.str() 很重要,即

MyClass data("hello", 6, true);
std::stringstream os;
{
cereal::JSONOutputArchive archive_out(os);
archive_out(CEREAL_NVP(data));
}
string json_str = os.str();
cout << json_str << endl;

// deserialize
std::stringstream is(json_str);
MyClass data_new;
{
cereal::JSONInputArchive archive_in(is);
archive_in(data_new);
cout << data_new.y << endl;
}

这是工作代码。您可能希望根据需要进一步更改它

关于c++ - 使用 Cereal 反序列化 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47297648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com