首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Cereal反序列化JSON字符串

使用Cereal反序列化JSON字符串
EN

Stack Overflow用户
提问于 2017-11-15 00:43:52
回答 1查看 6.5K关注 0票数 4

我是Cereal的新手,我很难理解如何反序列化JSON字符串。不幸的是,我的工作防火墙限制我不能访问谷歌组在留言板上发布。

我有一个类,我可以将其转换为JSON字符串,但在我的一生中,不能接受这个字符串并重新创建这个类。任何帮助都会受到感谢,请温柔一点--我刚从学校毕业,这是我的第一份工作,我的工作已经超出了我的深度。

这是我正在犯的错误:

在抛出‘what::RapidJSONException’的实例之后调用的终止:什么():rapidjson内部断言失败: IsObject()

下面是MyClass.hpp类:

代码语言:javascript
复制
#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:

代码语言:javascript
复制
#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 );
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-15 02:17:51

根据谷物文件

谷物中的一些档案只有在销毁后才能安全地冲洗它们的内容。确保,特别是对于输出序列化,您的存档是自动销毁的,当你完成它。

因此,在序列化块之外调用os.str()是非常重要的,即

代码语言:javascript
复制
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;
}

这是工作密码。你可能想根据你的需要进一步改变它。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47297648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档