I would like my program to save and read a Config structure in a JSON file.
However, I have a problem with generating the correct JSON file. Probably the problem is inheritance.
JSON Output (Incorrect):
{
"config": {
"confVector": [
{
"common": "a"
},
{
"common": "b"
}
]
}
}
Expected (correct) JSON:
{
"config": {
"confVector": [
{
"common": "a",
"a" : 1
},
{
"common": "b",
"b" : "b"
}
]
}
}
Code :
Base struct with common element
struct Base
{
std::string common;
template <class Archive>
void serialize(Archive &ar)
{
ar(CEREAL_NVP(common));
}
};
Two specific structures
struct A : public Base
{
int a;
template <class Archive>
void serialize(Archive &ar)
{
ar(cereal::make_nvp("Base", cereal::base_class<Base>(this)));
ar(cereal::make_nvp("a", a));
}
};
struct B : public Base
{
std::string b;
template <class Archive>
void serialize(Archive &ar)
{
ar(cereal::make_nvp("Base", cereal::base_class<Base>(this)));
ar(cereal::make_nvp("b", b));
}
};
struct Config
{
std::vector<Base> confVector;
template <class Archive>
void serialize(Archive &ar)
{
ar(CEREAL_NVP(confVector));
}
};
CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, A)
CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, B)
Main: test save to json file
int main()
{
std::string workPath = MAKE_STR(PLC_PROGRAM);
Config config;
A a;
a.a = 1;
a.common = "a";
B b;
b.b = "b";
b.common = "b";
config.confVector.push_back(a);
config.confVector.push_back(b);
std::ofstream outstream;
outstream.open(workPath + "/test.json");
{
cereal::JSONOutputArchive ar(outstream);
ar(cereal::make_nvp("config", config));
}
outstream.close();
}