nlohmann::json usage with better_enum



是否可以使用更好的enum(https://github.com/aantron/better-enums)与nlohmann::json(https://github.com/nlohmann/json)?

我正试图将整数/短字段迁移到better_enum生成的类。我确实尝试添加to_json和from_json方法,我仍然在编译时收到。

错误:static_assert由于需求而失败'std::is_default_constructiblestudents::GRADE::value' "类型必须为当与get()">

一起使用时,DefaultConstructible

下面是我的代码示例,我试图使用

Student.hpp

namespace students {
BETTER_ENUM(GRADE, short,
GRADE_1,
GRADE_2)
struct Student {
std::string name;
GRADE grade;
};
inline nlohmann::json get_untyped(const nlohmann::json &j, const char *property) {
if (j.find(property) != j.end()) {
return j.at(property).get<nlohmann::json>();
}
return {};
}
inline nlohmann::json get_untyped(const nlohmann::json &j, const std::string &property) {
return get_untyped(j, property.data());
}
void from_json(const nlohmann::json &j, students::GRADE &x);
void to_json(nlohmann::json &j, const students::GRADE &x);
void from_json(const nlohmann::json &j, students::Student &x);
void to_json(nlohmann::json &j, const students::Student &x);
inline void students::from_json(const nlohmann::json &j, GRADE &x) {
x = GRADE::_from_integral(j.at("grade").get<short>());
}
inline void students::to_json(nlohmann::json &j, const GRADE &x) {
j["grade"] = x._to_integral();
}
inline void from_json(const nlohmann::json &j, students::Student &x) {
x.name = j.at("name").get<std::string>();
x.grade = j.at("grade").get<GRADE>();
}
inline void to_json(nlohmann::json &j, const students::Student &x) {
j = nlohmann::json::object();
j["name"] = x.name;
j["grade"] = x.grade;
}
}

文件存储代码:

students::Student student1 = {"vs", students::GRADE::GRADE_1};
nlohmann::json jsonObject = student1;
std::ofstream studentFile("/Users/vs/Projects/test/data/students.json");
studentFile << std::setw(4) << jsonObject << std::endl;

是。来自nlohmann::json的文档:

如何使用get()非默认的可构造/不可复制类型?

有一种方法,如果你的类型是MoveConstructible。您还需要专门化adl_serializer,但要使用特殊的from_json重载。

在这种情况下,您可能想要这样做:

namespace nlohmann {
template<>
struct adl_serializer<students::GRADE> {
static students::GRADE from_json(const json &j) {
return students::GRADE::_from_integral(j.get<int>());
}
static void to_json(json &j, students::GRADE t) {
j = t._to_integral();
}
};
}

最新更新