如何将此类序列化为XML或JSON

How to serialize this class into XML or JSON

本文关键字:XML JSON 序列化      更新时间:2023-10-16

我有一个来自名为"校园"的类的对象列表,其中包含两个字符串,一个int和两个列表:一个用于"学生",另一个是"老师",在关闭程序之前,我想保存校园对象,当然还有列表中包含的"学生"answers"老师"对象,我想以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;
};

您可以使用此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);

不幸的是,C 不支持反射,因此它无法自动弄清参数名称。.但是请查看此答案,看起来它将接近您想要的内容:https://stackoverflow.com/a/19974486/1715829