为了将 JSON 反序列化为 c++ 类,我使用了 Cereal,它使用 RapidJSON。正如预期的那样,c++ std::string 不能有空值。但是其他平台确实支持字符串的空值(.NET SQL 等),我从它们那里得到带有空值字符串的 JSON。我需要容忍这一点,只需为空值创建一个空字符串。最好的方法是什么?
我默认将 JSON 上的字符串替换为“”,如下所示,但这不是一个干净的解决方案。
#include <cereal/archives/json.hpp>
#include <boost/algorithm/string.hpp>
// i.e. substitue all ":null with ":"" Like {"key":null} into {"key":""}
boost::replace_all(json, "\":null", "\":\"\"");
auto r = std::make_shared<R>();
std::stringstream ss(json);
{
cereal::JSONInputArchive archive(ss);
r->serialize(archive);
}
如果有人根据 Cereal 生成的异常查找此答案,则为:“rapidjson 内部断言失败:IsString()”