Maps with enum keys, such as std::map<E, T>, are stored as arrays of [key, value] pairs, because enums are not convertible to the string type of object keys - even if NLOHMANN_JSON_SERIALIZE_ENUM maps them to strings (#4378). The new JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS macro stores them as objects instead, converting each key with the enum's to_json. It applies to any map-like type with enum keys (std::map with any comparator, std::unordered_map, ...). A key that does not convert to a string throws type_error.302, and two keys converting to the same string throw the new type_error.318, rather than losing an entry. The macro changes the output of inline functions, so it is part of the ABI tag (_ekmo). Reading needs no macro: std::map and std::unordered_map with enum keys are now also read from objects, converting each key with the enum's from_json. That input was rejected before, and arrays of pairs are still read, so data written either way can be read. This supersedes #4531, which first proposed storing these maps as objects. Co-authored-by: Muhammad Amir bin Mohamad Ghazaly <amirghaz@umich.edu> Signed-off-by: Niels Lohmann <mail@nlohmann.me>
3.3 KiB
Specializing enum conversion
By default, enum values are serialized to JSON as integers. In some cases, this could result in undesired behavior. If the integer values of any enum values are changed after data using those enum values has been serialized to JSON, then deserializing that JSON would result in a different enum value being restored, or the value not being found at all.
It is possible to more precisely specify how a given enum is mapped to and from JSON as shown below:
// example enum type declaration
enum TaskState {
TS_STOPPED,
TS_RUNNING,
TS_COMPLETED,
TS_INVALID=-1,
};
// map TaskState values to JSON as strings
NLOHMANN_JSON_SERIALIZE_ENUM( TaskState, {
{TS_INVALID, nullptr},
{TS_STOPPED, "stopped"},
{TS_RUNNING, "running"},
{TS_COMPLETED, "completed"},
})
The NLOHMANN_JSON_SERIALIZE_ENUM() macro declares a set of
to_json() / from_json() functions for type TaskState while avoiding repetition and boilerplate serialization code.
Usage
// enum to JSON as string
json j = TS_STOPPED;
assert(j == "stopped");
// json string to enum
json j3 = "running";
assert(j3.get<TaskState>() == TS_RUNNING);
// undefined json value to enum (where the first map entry above is the default)
json jPi = 3.14;
assert(jPi.get<TaskState>() == TS_INVALID );
Maps with enum keys
By default, maps with enum keys, such as std::map<TaskState, std::string>, are stored as arrays of [key, value]
pairs, because JSON object keys must be strings. Define
JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS before including the
library to store them as objects, with the keys converted by the enum's to_json() function:
std::map<TaskState, std::string> m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
json j = m;
// default: [["stopped","aa"],["completed","bb"]]
// with JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS: {"completed":"bb","stopped":"aa"}
Either form can be read back, with or without the macro.
Notes
Just as in Arbitrary Type Conversions above,
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.- It MUST be available (e.g., proper headers must be included) everywhere you use the conversions.
Other Important points:
- When using
get<ENUM_TYPE>(), undefined JSON values will default to the first pair specified in your map. Select this default pair carefully. If you desire an exception in this circumstance useNLOHMANN_JSON_SERIALIZE_ENUM_STRICT()which behaves identically except for throwing an exception on unrecognized values. - 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.
- To disable the default serialization of enumerators as integers and force a compiler error instead, see
JSON_DISABLE_ENUM_SERIALIZATION.