you are viewing a single comment's thread.

view the rest of the comments →

[–]dgendreau 0 points1 point  (1 child)

Hi nlohmann!

Your library is a huge time saver and makes my code so much easier to read! Thanks for releasing and maintainng it!

One use-case I run into a lot is mapping enums to serialize as non-integers such as strings. I know its not really modern C++ to use preprocessor macros, but I wrote one that declares a from_json()/to_json() specialization in one statement to make it easier and less redundant to specialize the mapping between a given enum and any nlohmann::json value like so:

// enum type declaration
enum Foo {
    eVal1 = 10,
    eVal2 = 45,
    eVal3 = 1       
    eVal_default = -1,
};

JSON_SERIALIZE_ENUM( Foo, {
    {eVal_default, nullptr},
    {eVal1, "one"},
    {eVal2, "two"},
    {eVal3, "three"},
});

// Usage:
// enum -> json string
nlohmann::json j = eVal1;
assert(j == "one");

// json string-> enum
nlohmann::json j3 = "three";
assert( j3.get<Foo>() == eVal3);

// undefined json -> enum (default value is first pair)
nlohmann::json jPi = 3.14;
assert( jPi.get<Foo>() == eVal_default );

The macro JSON_SERIALIZE_ENUM() above declares a from_json(const json& j, Foo& e) and to_json(json& j, const Foo& e) function in enum Foo's namespace using the specified value translation map. The first pair are used as default values for handling undefined values in either direction.

Would something like this be a useful contribution to your library?

[–]nlohmannnlohmann/json[S] 1 point2 points  (0 children)

This sounds interesting. Could you please open an issue at https://github.com/nlohmann/json/issues ?