// // Created by selim on 06.11.22. // #ifndef AUTOCAT_GNOME_JSONOPTIONAL_H #define AUTOCAT_GNOME_JSONOPTIONAL_H #include #include namespace nlohmann { template void optional_to_json(J& j, const char* name, const std::optional& value) { if (value) { j[name] = *value; } } template void optional_from_json(const J& j, const char* name, std::optional& value) { const auto it = j.find(name); if (it != j.end()) { if(j.at(name).is_null()) { value = std::nullopt; } else { value = it->template get(); } } else { value = std::nullopt; } } template constexpr bool is_optional = false; template constexpr bool is_optional> = true; template void extended_to_json(const char *key, nlohmann::json &j, const T &value) { if constexpr (is_optional) optional_to_json(j, key, value); else j[key] = value; } template void extended_from_json(const char *key, const nlohmann::json &j, T &value) { //std::cout << "parsing key " << key << std::endl; if constexpr (is_optional) { optional_from_json(j, key, value); } else { j.at(key).get_to(value); } } #define EXTEND_JSON_TO(v1) extended_to_json(#v1, nlohmann_json_j, nlohmann_json_t.v1); #define EXTEND_JSON_FROM(v1) extended_from_json(#v1, nlohmann_json_j, nlohmann_json_t.v1); #define NLOHMANN_JSONIFY_ALL_THINGS(Type, ...) \ friend void to_json(nlohmann::json &nlohmann_json_j, const Type &nlohmann_json_t) { \ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(EXTEND_JSON_TO, __VA_ARGS__)) \ } \ friend void from_json(const nlohmann::json &nlohmann_json_j, Type &nlohmann_json_t) { \ NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(EXTEND_JSON_FROM, __VA_ARGS__)) \ } } #endif //AUTOCAT_GNOME_JSONOPTIONAL_H