1 #include <iostream>
2 #include <nlohmann/json.hpp>
3 
4 using json = nlohmann::json;
5 
6 namespace ns
7 {
8 enum TaskState
9 {
10     TS_STOPPED,
11     TS_RUNNING,
12     TS_COMPLETED,
13     TS_INVALID = -1
14 };
15 
16 NLOHMANN_JSON_SERIALIZE_ENUM(TaskState,
17 {
18     { TS_INVALID, nullptr },
19     { TS_STOPPED, "stopped" },
20     { TS_RUNNING, "running" },
21     { TS_COMPLETED, "completed" }
22 })
23 
24 enum class Color
25 {
26     red, green, blue, unknown
27 };
28 
29 NLOHMANN_JSON_SERIALIZE_ENUM(Color,
30 {
31     { Color::unknown, "unknown" }, { Color::red, "red" },
32     { Color::green, "green" }, { Color::blue, "blue" }
33 })
34 } // namespace ns
35 
main()36 int main()
37 {
38     // serialization
39     json j_stopped = ns::TS_STOPPED;
40     json j_red = ns::Color::red;
41     std::cout << "ns::TS_STOPPED -> " << j_stopped
42               << ", ns::Color::red -> " << j_red << std::endl;
43 
44     // deserialization
45     json j_running = "running";
46     json j_blue = "blue";
47     auto running = j_running.get<ns::TaskState>();
48     auto blue = j_blue.get<ns::Color>();
49     std::cout << j_running << " -> " << running
50               << ", " << j_blue << " -> " << static_cast<int>(blue) << std::endl;
51 
52     // deserializing undefined JSON value to enum
53     // (where the first map entry above is the default)
54     json j_pi = 3.14;
55     auto invalid = j_pi.get<ns::TaskState>();
56     auto unknown = j_pi.get<ns::Color>();
57     std::cout << j_pi << " -> " << invalid << ", "
58               << j_pi << " -> " << static_cast<int>(unknown) << std::endl;
59 }
60