Not serialising to JSON/XML of key/value pairs if the value is at a default

35 views
Skip to first unread message

Bruno Nicoletti

unread,
Aug 27, 2021, 5:18:54 AM8/27/21
to cereal serialization library
Is there a way to get cereal to elide key/value pairs from a JSON/XML stream if the value is at some default? This will save on size of the created archive which is useful if you have lots of values set to a default...

If not, I'd like to suggest an extension, so something like...

struct MyStruct {
public:
  int   i;
  float f;
  std::string s;

  template<class Archive>
  void serialize(Archive& ar)
  {
    ar(cereal::make_nvp_withdefault("i", i, 0));
    ar(cereal::make_nvp_withdefault("f", f, 1.0f));
    ar(cereal::make_nvp_withdefault("f", f, std::string()));
  }
};

So if we serialised a MyStruct where 'i' was still at the default of 0, the archivers would elide that key from the JSON and we would get....

{
  "MyStruct" : {
    "f" : 22.2,
    "s" : "bananas"
   }
}

When loading that archive it would see key was missing and then set the value to the specified default.

tx

b

Reply all
Reply to author
Forward
0 new messages