1

我有一个从名为“Campus”的类派生的对象列表,其中包含两个字符串,一个 int 和两个列表:一个用于“学生”,另一个用于“教师”,在关闭程序之前,我想保存校园对象,当然还有列表中包含的“学生”和“教师”对象,我想以 XML 或 JSON 格式甚至其他任何格式序列化这些数据,然后将结果存储在文件中。

有人可以给我最快的方法来使用 XML 或 JSON 或其他解决方案中的库(不像 boost 那么重)进行序列化。说到处理JSON或XML序列化,我不知道该怎么办!编辑:这对 RapidJSON 可行吗?

class Campus
{
private:
    std::string city;
    std::string region;
    int capacity;
    std::list<Student> students;
    std::list<Teacher> teachers;
}

class Student
{
private:
    int ID;
    std::string name;
    std::string surname;
}

class Teacher
{
protected:
    int ID;
    std::string name;
    std::string surname;
};
4

2 回答 2

2

您可以使用这个 C++ 序列化库: Pakal persist

#include "XmlWriter.h"


class Campus
{
private:
    std::string city;
    std::string region;
    int capacity;
    std::list<Student> students;
    std::list<Teacher> teachers;

public:

    void persist(Archive* archive)
    {
        archive->value("city",city);
        archive->value("region",region);
        archive->value("capacity",capacity);

        archive->value("Students","Student",students);
        archive->value("Teachers","Teacher",teachers);
    }

}

class Student
{
private:
    int ID;
    std::string name;
    std::string surname;

public:

    void persist(Archive* archive)
    {
        archive->value("ID",ID);
        archive->value("surname",surname);
        archive->value("name",name);        
    }

}

class Teacher
{
protected:
    int ID;
    std::string name;
    std::string surname;
public:

    void persist(Archive* archive)
    {
        archive->value("ID",ID);
        archive->value("surname",surname);
        archive->value("name",name);
    }
};

Campus c;

XmlWriter writer;
writer.write("campus.xml","Campus",c);
于 2015-11-18T21:42:16.630 回答
0

不幸的是,C++ 不支持反射,所以它不能自动找出参数名称。但是看看这个答案,它看起来会接近你想要的:https ://stackoverflow.com/a/19974486 /1715829

于 2015-05-08T22:19:24.410 回答