Search code examples
c++xmljsonserializationrapidjson

How to serialize this class into XML or JSON


I have a list of objects derived from a class named "Campus" which contains two strings, one int and two lists : one for "Students", the other is for "Teachers", before closing the program, I want to save the campus objects and of course the "Student" and "Teachers" objects contained on their lists, I want to serialize those data in an XML or JSON format or even anything else then store the result in a file.

Can somebody give me the fastest way to do the serialization with a library (that is not heavy as boost) in XML or JSON or another solution. When it comes to deal with JSON or XML serialization, I don't know what to do ! EDIT: is this feasible with 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;
};

Solution

  • You can use this C++ serialization library : 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);