【问题标题】:c++ How to serialize class to json and parse the json file?c ++如何将类序列化为json并解析json文件?
【发布时间】:2016-03-23 21:36:00
【问题描述】:

我有一个 xObject 类,它基本上是一个微不足道的“人”类,我希望能够将整个类序列化为一个 .json 文件,然后读取该文件以便能够从文件并将这些变量链接到类的名称。

例如:

xObject 类代码:

class xObject{
    string name;
    string lastname;
    int age;

    public:
        string getName(){
            return name;
        }
        string getLastname(){
            return lastname;
        }
        int getAge(){
            return age;
        }
}

然后我创建一个带有一些属性的对象。

int main(){

    xObject homer;
    homer.name = "Homer";
    homer.lastname = "Simpson";
    homer.age = 30;

    //SERIALIZATION OF HOMER.
    homer.serialExport("File.json")

    return 0;
}

所以现在,我的 File.json 应该是这样的:

{"homer" :
    {"name" : "Homer"
     "lastname" : "Simpson"
     "age" : 30
    }
}

然后,我希望能够从文件中读取数据以从中提取数据,如下所示:

int main(){

    xObject bart;
    bart.name = "Bart";
    //ACTUAL USE OF THE .JSON FILE HERE
    myFile = ("File.json");
    bart.lastname = Deserializer(myFile).getLastname(); //It is supossed to assign "Simpson" 
                                                        //to the lastname reading from the serialized 
                                                        //homer class file described above.
    bart.age = Deserializer(myFile).getAge() - 20; //Sets homer's age minus 20 years.

    return 0;
}    

那么,我如何在 C++ 上做到这一点? (接受库实现)

我怎样才能检索已序列化的类名?

例如Deserialize(myFile).getClassName() 应该返回"homer"

我在 java 中使用 XML 序列化做过类似的事情,而且非常简单,但在 C++ 中这似乎不太容易做到,而且我对 C++ 还比较陌生。

【问题讨论】:

    标签: c++ json parsing serialization deserialization


    【解决方案1】:

    在 c++ 中没有自省/反射,因此如果没有在流中显式写入成员变量,就无法自动序列化一个类。同理,已经序列化的类名是取不出来的。

    所以解决方案是在你的类中写一个函数,序列化你想要的成员变量。

    当然,您不会重新发明轮子以将您的文件格式化为 json。您可以使用:https://github.com/open-source-parsers/jsoncpp

    例如你可以写:

    Json::Value root;
    root["homer"]["name"]="Homer";
    root["homer"]["lastname"]="Simpson";
    //etc
    
    ofstream file;
    file.open("File.json"); 
    file << root;           
    file.close();
    

    但是,对于阅读,您可以随心所欲:

    Json::Value root2;
    ifstream file2;
    file2.open("File.json");
    file2 >> root2;
    file2.close();
    
    xObject homer;
    homer.lastname = root2["homer"]["lastname"].toStyledString();
    //etc
    

    当然,您的属性必须是公开的。否则,您需要添加一个 setter 函数。

    【讨论】:

    • 成功了。我编辑了您在答案中的一些拼写错误,并在 fstream 调用的 i/o 中多写了几行。谢谢。
    • 我在飞机上用手机写了这个答案;)
    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 2021-12-18
    • 2020-07-13
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多