Advanced serialization macros #2588
Replies: 2 comments
-
The above can be extended in various ways, for example:
Referencing #2587 the issue there can also be fixed this way. For example, to allow parsing nulls as default values, one simply needs to modify it like so: namespace json {
using json = nlohmann::json;
template <class T>
void get_to_allow_null(const json& jv, T& v)
{
jv.is_null() ? v = T() : jv.get_to(v);
}
template <class T>
void get_value(const json& j, const char* n, T& v)
{
get_to_allow_null(j.at(n), v);
}
template <class T>
void get_value(const json& j, const char* n, T& v, const T& d)
{
if (const auto it = j.find(n); it != j.end())
get_to_allow_null(*it, v);
else
v = d;
}
} Using the above will create default constructed values in case a null is encountered. Other extensions are possible, like adding additional traits/flags to individual fields, etc., and modifying json::get_value() above accordingly. |
Beta Was this translation helpful? Give feedback.
-
Updated macros, more generic, only get_value() template functions need to be added above in case more arguments are desired per field. Should work with recent compilers, MSVC included (given /Zc:preprocessor).
|
Beta Was this translation helpful? Give feedback.
-
NOTE: Updated macros are in later comments!
The JSON_SERIALIZE() macro above allows specifying default values in case a key does not exist. It is intended as a replacement for NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE().
It needs standard compliant preprocessor, so for MSVC you must enable /Zc:preprocessor for it to work.
Use like so:
Feel free to use/enhance it as you want.
Beta Was this translation helpful? Give feedback.
All reactions