使用 Cereal 反序列化 JSON 字符串
Using Cereal to deserialize a JSON string
我是谷物的新手,我很难理解如何反序列化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;
};
以下是我的主要.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 );
}
}
根据谷物文档
因此,在一些谷物档案只有在销毁后才能安全地完成冲洗其内容物。确保(尤其是对于输出序列化(存档在完成存档后自动销毁存档。
序列化块之外调用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;
}
这是工作代码。您可能希望根据需要进一步更改它
相关文章:
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- 使用 jsoncpp 解析 json 数组字符串
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- POCO C++对象到 JSON 字符串序列化
- 将可变参数模板参数转换为 JSON 字符串
- 构造一个类似于JSON文件c++的字符串
- 从 json 字符串将 QVariant 转换为 QList<MyClass>
- C++中的 Json:将数字解析为字符串以避免浮点不准确
- 使用 Json 转换器反序列化 WCF 服务中的C++字符串
- 如何使用 boost 属性树来解析 boost 中 json 字符串中的数组中的元素?
- Boost.Hana JSON 示例:字符串和 decltype(std::to_string(..))之间的区别
- 我想将字符串转换为 Json 格式并返回字符串向量作为答案
- 如何在Visual Studio Code tasks.json中定义C++字符串宏?
- 使用Python将C 结构更改为JSON字符串
- 如何提取由特定模式分开的JSON对象字符串
- 使用RapidJson凝结JSON文件后,如何将输出存储在C 字符串中
- 如何将变量用作原始 JSON 字符串中的数据?
- 当 JSON 值应为 INT 但以字符串类型发送时,RapidJSON 崩溃
- 无法区分 JSON 对象/数组/字符串