0

I'm using cereal with c++ to serialise and deserialise JSON. My Json objects all have a base class, this sort of maps to the JSON like so...

["baseclass_var1", "baseclass_var2", 21321, {"derived_object_var1":"blah", "derived_object_var2":"blahblah"}]

The derived class contributes the JSON object at the end of this JSON array and the base class contributes the values within the array.

My classes look approximately like this,

struct baseObject
{
    baseObject() 
    {
    }

    template<typename Archive>
    void serialize(Archive& archive)
    {
        archive.makeArray();
        archive("baseclass_var1", "baseclass_var2", 21321);
    }
};

struct derivedObject : baseObject
{
    template<typename Archive>
    void serialize(Archive& archive)
    {
        baseObject::serialize(archive);
        archive.startNode();
        cereal::nvp(archive, "derived_object_var1", "blah");
        cereal::nvp(archive, "derived_object_var2", "blahblah");
        archive.finishNode();
    }
}

I can't help but feel like considering how easy cereal is to use, where the structure of the JSON is implicitly defined, I might be making a mistake by having to explicitly call startNode(), finishNode() and makeArray()? Is there an alternative implementation that would take care of the JSON structure for me, without having to explicitly state where I want the sub node to be?

Alex
  • 669
  • 15
  • 37
  • Why are you explicitly starting an array and a sub node? Usually you map those to your class fields and cereal handles file structure for you. If you want to serialize an array, pass a `std::vector` or a `std::array` to the archive, i.e. `archive(CEREAL_NVP(my_array));` – Timo Apr 06 '20 at 12:50
  • OK - that's my question, I'm aware that that's what the documentation suggests. But the types in the array are all different, primitive types, which would preclude using that method, say a std::vector, unless there's a particular way serial uses to get around that? One of those elements in the array, is a sub object, populated with values from the derived class. – Alex Apr 06 '20 at 12:56
  • 1
    Oh ok that's a different case then. But why would you want to map different types to one array? Are those types derived from a common class? You could also make a `vector>` and pass that to the archive. – Timo Apr 06 '20 at 13:00
  • That's a reasonable question, and thanks for your help Timo. Unfortunately I'm following a standard for the JSON, so I don't have any choice over changing the JSON representation, but I can change the C++ code. I'll have a look to see if using a variant would improve the implementation, I guess that variant could also take a pointer to the base class of the derived objects. – Alex Apr 06 '20 at 13:06
  • 1
    That won't work, the variant needs to know which of its alternatives is stored in the JSON so it has to add additional data to it. I'm afraid you're stuck with your solution then. – Timo Apr 06 '20 at 14:22

0 Answers0