问题描述
为了使用https://github.com/nlohmann/json进行解析,
std::vector<std::shared_ptr<VPN>>
其中VPN可以是子类型OpenVPN
和其他类型,例如MicrosoftVPN
,CiscoVPN
等,我必须执行以下操作:
void to_json(json &j,const std::shared_ptr<VPN> &p)
{
//Dont forget to set type on each subtype!!!
if (auto pp = std::dynamic_pointer_cast<OpenVPN>(p))
{
to_json(j,pp);
}
else
{
//try other subtypes then throw if none
}
}
void from_json(const json &j,std::shared_ptr<VPN> &p)
{
if (j.at("type") == "OPENVPN")
{
p = std::make_shared<OpenVPN>();
//Important: re-set the type since we recreated the instance
p->type = VPN::Type::OPENVPN;
auto pp = std::dynamic_pointer_cast<OpenVPN>(p);
from_json(j,pp);
}
else
{
//throw
}
}
然后,对于每个子类型,我都实现to_json
和from_json
:
void to_json(json &j,const std::shared_ptr<OpenVPN> &p)
{
//Important: always set type
j = json{
{"type",p->type},{"openvpnVersion",p->openvpnVersion},{"profile",p->profile}};
//...
}
void from_json(const json &j,std::shared_ptr<OpenVPN> &p)
{
j.at("openvpnVersion").get_to(p->openvpnVersion);
j.at("profile").get_to(p->profile);
//...
}
如您所见,我遇到了很多问题,例如if (j.at("type") == "OPENVPN")
。例如,在创建子类型为VPN
的{{1}}实例之前,必须与字符串文字而不是枚举进行比较。经过很多段错误后,我进行了多次尝试,以了解自己在做什么。另外,我必须自己实例化指针,这很容易忘记并导致段错误。
显然,OpenVPN
的工作原理使我无需执行任何操作,除了为std::vector<CustomObject>
实现from_json
和to_json
之外。但是如果使用CustomObject
,那么我需要为CustomObject = std::shared_ptr<OtherCustomObject>
实现from_json
和to_json
。
图书馆是否应该独自处理std::shared_ptr<OtherCustomObject>
?有人有更好的解决方案吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)