0

我应该如何继续序列化嵌套对象?

例子:

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? )
    }  
}

主要思想是有类似的东西

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

顺便说一句,我可以问第二个问题。我可以从这样的 json 中再次获得 A 对象吗?谢谢各位=)

4

1 回答 1

1

您需要做的就是包括对序列化std::vector( #include <cereal/types/vector.hpp>) 的支持并将其添加到对存档的调用中:

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

这是一个完整的示例,它还显示了如何保存到 JSON,然后将数据加载回:

#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);
  }
}

作为输出:

{
    "value0": {
        "x": 3,
        "nested": [
            {
                "y": 3
            },
            {
                "y": 2
            },
            {
                "y": 1
            }
        ]
    }
}
{
    "value0": {
        "x": 3,
        "nested": [
            {
                "y": 3
            },
            {
                "y": 2
            },
            {
                "y": 1
            }
        ]
    }
}
于 2016-10-17T19:50:55.267 回答