0

How should I proceed to serialize a nested object?

Example:

class B
{
public:
    int y;

    template<class Archive>
    void serialize(Archive& ar)
    {
        ar(CEREAL_NVP(y));
    }
}

class A
{
public:
    int x;
    std::vector<B> nested;

    template<class Archive>
    void serialize(Archive& ar)
    {
        ar(CEREAL_NVP(x) what about nested? )
    }  
}

The main idea is to have something like

{
   "x": ...
   "nested": [
      {
         "y": ...
      },
      {
         "y": ...
      }
   ]
}

By the way, a second question if I may. Can I from a json like this get an A object again? Thank you guys =)

1 Answers1

1

All you need to do is include support for serializing std::vector (#include <cereal/types/vector.hpp>) and add it to your call to the archive:

ar(CEREAL_NVP(x), CEREAL_NVP(nested));

Here is a full example that also shows how to save to JSON and then load the data back:

#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp>

class B
{
  public:
    int y;

    template<class Archive>
    void serialize(Archive& ar)
    {
      ar(CEREAL_NVP(y));
    }
};

class A
{
  public:
    int x;
    std::vector<B> nested;

    template<class Archive>
    void serialize(Archive& ar)
    {
      ar(CEREAL_NVP(x), CEREAL_NVP(nested) );
    }
};

int main()
{
  std::stringstream ss;
  {
    cereal::JSONOutputArchive ar(ss);
    A a = {3, {{3},{2},{1}}};
    ar( a );
  }

  std::cout << ss.str() << std::endl;

  {
    cereal::JSONInputArchive ar(ss);
    A a;
    ar( a );

    cereal::JSONOutputArchive ar2(std::cout);
    ar2(a);
  }
}

which gives as output:

{
    "value0": {
        "x": 3,
        "nested": [
            {
                "y": 3
            },
            {
                "y": 2
            },
            {
                "y": 1
            }
        ]
    }
}
{
    "value0": {
        "x": 3,
        "nested": [
            {
                "y": 3
            },
            {
                "y": 2
            },
            {
                "y": 1
            }
        ]
    }
}
Azoth
  • 1,652
  • 16
  • 24