tagval 0.2.0
Modern C++23 header-only library of tagged values (open/closed enumerations with metadata)
Loading...
Searching...
No Matches
json_nlohmann.hpp
Go to the documentation of this file.
1#pragma once
2
18
19#if !defined(TAGVAL_WITH_NLOHMANN_JSON)
20#if __has_include(<nlohmann/json.hpp>)
21#define TAGVAL_WITH_NLOHMANN_JSON 1
22#else
23#define TAGVAL_WITH_NLOHMANN_JSON 0
24#endif
25#endif
26
27#if TAGVAL_WITH_NLOHMANN_JSON
28
29#include <tagval/base.hpp>
30#include <tagval/error.hpp>
31
32#include <nlohmann/json.hpp>
33
34#include <concepts>
35#include <string>
36#include <string_view>
37
38namespace tagval {
39
40template <typename T>
41 requires std::derived_from<T, detail::TagValBaseTag>
42inline void to_json(::nlohmann::json& j, const T& v) {
43 j = std::string{v.code()};
44}
45
46template <typename T>
47 requires std::derived_from<T, detail::TagValBaseTag>
48inline void from_json(const ::nlohmann::json& j, T& v) {
49 const auto s = j.get<std::string>();
50 auto exp = T::try_of(std::string_view{s});
51 if (!exp) {
52 throw UnknownCodeError{exp.error().message()};
53 }
54 v = *exp;
55}
56
57} // namespace tagval
58
59#endif // TAGVAL_WITH_NLOHMANN_JSON
CRTP HandleBase used by ClosedEnded and OpenEnded.
Thrown by of() when a code is not present.
Definition error.hpp:19
tagval exception types and ParseError record used by try_of().
Definition base.hpp:26
void to_json(::nlohmann::json &j, const T &v)
Definition json_nlohmann.hpp:42
void from_json(const ::nlohmann::json &j, T &v)
Definition json_nlohmann.hpp:48