Skip to content

Instantly share code, notes, and snippets.

@ITotalJustice
Created November 9, 2021 18:00
Show Gist options
  • Save ITotalJustice/b92a8a2ab09aee9d09f58072c650ec45 to your computer and use it in GitHub Desktop.
Save ITotalJustice/b92a8a2ab09aee9d09f58072c650ec45 to your computer and use it in GitHub Desktop.
nlohmann::json helper
#include "json.hpp"
#include <optional>
using json = nlohmann::json;
namespace nlohmann {
// https://github.com/nlohmann/json/issues/1910#issuecomment-615843605
template <typename T>
struct adl_serializer<std::optional<T>> {
static inline void to_json(json& j, const std::optional<T>& opt) {
if (opt == std::nullopt) {
j = nullptr;
} else {
j = *opt;
}
}
static inline void from_json(const json& j, std::optional<T>& opt) {
if (j.is_null()) {
opt = std::nullopt;
} else {
opt = j.get<T>();
}
}
};
template <typename Json, typename T>
static constexpr inline void JSON_SET(const Json& j, const char* s, T& t) {
if (j.contains(s)) {
j.at(s).get_to(t);
}
}
} // namespace nlohmann
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment