1#include <iostream> 2#include <nlohmann/json.hpp> 3 4using json = nlohmann::json; 5 6namespace ns 7{ 8enum TaskState 9{ 10 TS_STOPPED, 11 TS_RUNNING, 12 TS_COMPLETED, 13 TS_INVALID = -1 14}; 15 16NLOHMANN_JSON_SERIALIZE_ENUM(TaskState, 17{ 18 { TS_INVALID, nullptr }, 19 { TS_STOPPED, "stopped" }, 20 { TS_RUNNING, "running" }, 21 { TS_COMPLETED, "completed" } 22}) 23 24enum class Color 25{ 26 red, green, blue, unknown 27}; 28 29NLOHMANN_JSON_SERIALIZE_ENUM(Color, 30{ 31 { Color::unknown, "unknown" }, { Color::red, "red" }, 32 { Color::green, "green" }, { Color::blue, "blue" } 33}) 34} // namespace ns 35 36int 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