• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Specializing enum conversion
2
3By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.
4
5It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:
6
7```cpp
8// example enum type declaration
9enum TaskState {
10    TS_STOPPED,
11    TS_RUNNING,
12    TS_COMPLETED,
13    TS_INVALID=-1,
14};
15
16// map TaskState values to JSON as strings
17NLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {
18    {TS_INVALID, nullptr},
19    {TS_STOPPED, "stopped"},
20    {TS_RUNNING, "running"},
21    {TS_COMPLETED, "completed"},
22})
23```
24
25The `NLOHMANN_JSON_SERIALIZE_ENUM()` macro declares a set of `to_json()` / `from_json()` functions for type `TaskState` while avoiding repetition and boilerplate serialization code.
26
27## Usage
28
29```cpp
30// enum to JSON as string
31json j = TS_STOPPED;
32assert(j == "stopped");
33
34// json string to enum
35json j3 = "running";
36assert(j3.get<TaskState>() == TS_RUNNING);
37
38// undefined json value to enum (where the first map entry above is the default)
39json jPi = 3.14;
40assert(jPi.get<TaskState>() == TS_INVALID );
41```
42
43## Notes
44
45Just as in [Arbitrary Type Conversions](#arbitrary-types-conversions) above,
46
47- `NLOHMANN_JSON_SERIALIZE_ENUM()` MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it and it will default to integer serialization.
48- It MUST be available (e.g., proper headers must be included) everywhere you use the conversions.
49
50Other Important points:
51
52- When using `get<ENUM_TYPE>()`, undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.
53- If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.
54