sábado, 16 de abril de 2011

Implementing a JSON serializer using Boost.Fusion and Boost.Serialization (I)

Using Boost.Serialization, we have a generic way to serialize and load data, simply adding a template method "serialize" in our classes/structs.

Using Boost.Fusion (version equal or greater than 1.45.0), we have a generic way to access the fields of a struct and get their names.

The idea: using both we can implement a JSON serializer/deserializer with the usage bellow:

struct my_JSON_struct
{
    int my_integer;
    int my_array[2];
    std::string my_string;

    template < typename Archive >
    void serialize(Archive& ar, unsigned int version)
    {
        ar & my_integer;
        ar & my_array;
        ar & my_string;
    }
};

// ...

my_JSON_struct s1, s2;

// ...

// Saving data (os == ostream)
json_oarchive joa(os);
joa << s1;
// Resulting: {"my_integer" : 10, "my_array" : [1, 4], "my_string" : "nice string"}

// Loading data (is == istream)
json_iarchive jia(is);
jia >> s2;

To be continued...

No hay comentarios:

Publicar un comentario