Cereal - multiple de-serialization

0

I am very new to Cereal, and I have a (possible simple) question:

Is there a way to deserialize multiple objects when I don't know the number of objects inside the (XML) archive?

I tried something like:

std::ifstream is("c:\\data.xml");
cereal::XMLInputArchive archive(is);

while (is.good() && !is.eof())
{               
    try{
        ObjectIn oIn;
        archive(oIn);
        objectList.push_back(oIn);
    }
    catch (exception e){
    }
}

Let's say I have 3 objects in the XML file and the XML that I receive hasn't the containing object number. So, in my code, the first 3 iteration are OK, but the 4th generates "Unhandled exception at 0x0035395E in CerealTest.exe: 0xC0000005: Access violation reading location 0x00000018."

Do you have any suggestion?

c++
serialization
cereal
asked on Stack Overflow Apr 4, 2014 by Metallaru

1 Answer

2

Let me ask you a question before trying to answer your question: if you are serializing an unknown number of items, why not place those items in some container designed to hold a variable number of items? You could use an std::vector to store your ObjectIn and easily handle any number of them. Your code would look something like:

std::vector<MyObjects> vec;
{
  cereal::XMLInputArchive ar("filename");
  ar( vec );
} // get in the habit of using cereal archives in an RAII fashion

The above works with any number of objects serialized, assuming that cereal generated the XML to begin with. You can even add or remove elements from the vector in the XML code and it will work properly.


If you are insistent on reading some unknown number of objects and not placing them in a container designed to hold a variable number of elements, you can it something like this (but be warned this is not a good idea - you should really try to change your serialization strategy and not do this):

{
  cereal::XMLInputArchive ar("filename");
  try
  {
    while( true )
    {
      ObjectIn ob;
      ar( ob );
      objectList.push_back(oIn);
    }
  catch( ... )
  { }
}

Again let me stress that this is fundamentally a problem with your serialization strategy and you should be serializing a container instead of items a-la-carte if you don't know how many there will be. The above code can't handle reading in anything else, it just tries to blindly read things in until it encounters an exception. If your objects followed some naming pattern, you could use name-value-pairs (cereal::make_nvp) to retrieve them by name.

answered on Stack Overflow Apr 5, 2014 by Azoth

User contributions licensed under CC BY-SA 3.0