Overwork documentation (#3444)

* 📝 overwork macro documentation

* 📝 address review comments

* 🔧 add style check to Makefile

* 🙈 overwork .gitignore

* 📌 Pygments 2.12.0 is broken

* ✏️ fix links

* 🚸 adjust output to cppcheck

* 📝 add titles to more admonitions

* ✏️ fix typos

* 📝 document future behavior change
This commit is contained in:
Niels Lohmann
2022-04-25 22:40:45 +02:00
committed by GitHub
parent fcc36f99ba
commit a6ee8bf9d9
63 changed files with 1689 additions and 366 deletions

View File

@@ -1,22 +1,37 @@
# Macros
!!! note
Some aspects of the library can be configured by defining preprocessor macros **before** including the `json.hpp`
header. See also the [macro overview page](../../features/macros.md).
This page is under construction. See the [macro overview page](../../features/macros.md) until then.
## Runtime assertions
Some aspects of the library can be configured by defining preprocessor macros before including the `json.hpp` header.
- [**JSON_ASSERT(x)**](json_assert.md) - control behavior of runtime assertions
- [`JSON_ASSERT(x)`](json_assert.md)
- `JSON_CATCH_USER(exception)`
- `JSON_DIAGNOSTICS`
- `JSON_HAS_CPP_11`, `JSON_HAS_CPP_14`, `JSON_HAS_CPP_17`, `JSON_HAS_CPP_20`
- `JSON_NOEXCEPTION`
- `JSON_NO_IO`
- `JSON_SKIP_UNSUPPORTED_COMPILER_CHECK`
- `JSON_THROW_USER(exception)`
- `JSON_TRY_USER`
- `JSON_USE_IMPLICIT_CONVERSIONS`
- `NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)`
- `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)`
- `NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)`
- `NLOHMANN_JSON_VERSION_MAJOR`, `NLOHMANN_JSON_VERSION_MINOR`, `NLOHMANN_JSON_VERSION_PATCH`
## Exceptions
- [**JSON_CATCH_USER(exception)**<br>**JSON_THROW_USER(exception)**<br>**JSON_TRY_USER**](json_throw_user.md) - control exceptions
- [**JSON_DIAGNOSTICS**](json_diagnostics.md) - control extended diagnostics
- [**JSON_NOEXCEPTION**](json_noexception.md) - switch off exceptions
## Language support
- [**JSON_HAS_CPP_11**<br>**JSON_HAS_CPP_14**<br>**JSON_HAS_CPP_17**<br>**JSON_HAS_CPP_20**](json_has_cpp_11.md) - set supported C++ standard
- [**JSON_HAS_FILESYSTEM**<br>**JSON_HAS_EXPERIMENTAL_FILESYSTEM**](json_has_filesystem.md) - control `std::filesystem` support
- [**JSON_NO_IO**](json_no_io.md) - switch off functions relying on certain C++ I/O headers
- [**JSON_SKIP_UNSUPPORTED_COMPILER_CHECK**](json_skip_unsupported_compiler_check.md) - do not warn about unsupported compilers
## Library version
- [**JSON_SKIP_LIBRARY_VERSION_CHECK**](json_skip_library_version_check.md) - skip library version check
- [**NLOHMANN_JSON_VERSION_MAJOR**<br>**NLOHMANN_JSON_VERSION_MINOR**<br>**NLOHMANN_JSON_VERSION_PATCH**](nlohmann_json_version_major.md) - library version information
## Type conversions
- [**JSON_USE_IMPLICIT_CONVERSIONS**](json_use_implicit_conversions.md) - control implicit conversions
## Serialization/deserialization macros
- [**NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)**<br>**NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)**](nlohmann_define_type_intrusive.md) - serialization/deserialization of types _with_ access to private variables
- [**NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...)**<br>**NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...)**](nlohmann_define_type_non_intrusive.md) - serialization/deserialization of types _without_ access to private variables
- [**NLOHMANN_JSON_SERIALIZE_ENUM(type, ...)**](nlohmann_json_serialize_enum.md) - serialization/deserialization of enum
types

View File

@@ -1,11 +1,84 @@
# JSON_ASSERT(x)
# JSON_ASSERT
```cpp
JSON_ASSERT(x)
#define JSON_ASSERT(x) /* value */
```
## Default implementation
This macro controls which code is executed for [runtime assertions](../../features/assertions.md) of the library.
## Parameters
`x` (in)
: expression of scalar type
## Default definition
The default value is [`#!cpp assert(x)`](https://en.cppreference.com/w/cpp/error/assert).
```cpp
assert(x);
#define JSON_ASSERT(x) assert(x)
```
Therefore, assertions can be switched off by defining `NDEBUG`.
## Notes
- The library uses numerous assertions to guarantee invariants and to abort in case of otherwise undefined behavior
(e.g., when calling [operator[]](../basic_json/operator%5B%5D.md) with a missing object key on a `const` object). See
page [runtime assertions](../../features/assertions.md) for more information.
- Defining the macro to code that does not call `std::abort` may leave the library in an undefined state.
- The macro is undefined outside the library.
## Examples
??? example "Example 1: default behavior"
The following code will trigger an assertion at runtime:
```cpp
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
const json j = {{"key", "value"}};
auto v = j["missing"];
}
```
Output:
```
Assertion failed: (m_value.object->find(key) != m_value.object->end()), function operator[], file json.hpp, line 2144.
```
??? example "Example 2: user-defined behavior"
The assertion reporting can be changed by defining `JSON_ASSERT(x)` differently.
```cpp
#include <cstdio>
#include <cstdlib>
#define JSON_ASSERT(x) if(!(x)){fprintf(stderr, "assertion error in %s\n", __FUNCTION__); std::abort();}
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
const json j = {{"key", "value"}};
auto v = j["missing"];
}
```
Output:
```
assertion error in operator[]
```
## Version history
- Added in version 3.9.0.

View File

@@ -0,0 +1,67 @@
# JSON_DIAGNOSTICS
```cpp
#define JSON_DIAGNOSTICS /* value */
```
This macro enables [extended diagnostics for exception messages](../../home/exceptions.md#extended-diagnostic-messages).
Possible values are `1` to enable or `0` to disable (default).
When enabled, exception messages contain a [JSON Pointer](../json_pointer/json_pointer.md) to the JSON value that
triggered the exception. Note that enabling this macro increases the size of every JSON value by one pointer and adds
some runtime overhead.
The diagnostics messages can also be controlled with the CMake option `JSON_Diagnostics` (`OFF` by default) which sets
`JSON_DIAGNOSTICS` accordingly.
## Default definition
The default value is `0` (extended diagnostics are switched off).
```cpp
#define JSON_DIAGNOSTICS 0
```
When the macro is not defined, the library will define it to its default value.
## Notes
!!! danger "ABI incompatibility"
As this macro changes the definition of the `basic_json` object, it MUST be defined in the same way globally, even
across different compilation units: `basic_json` objects with differently defined `JSON_DIAGNOSTICS` macros are
not compatible!
## Examples
??? example "Example 1: default behavior"
```cpp
--8<-- "examples/diagnostics_standard.cpp"
```
Output:
```
--8<-- "examples/diagnostics_standard.output"
```
This exception can be hard to debug if storing the value `#!c "12"` and accessing it is further apart.
??? example "Example 2: extended diagnostic messages"
```cpp
--8<-- "examples/diagnostics_extended.cpp"
```
Output:
```
--8<-- "examples/diagnostics_extended.output"
```
Now the exception message contains a JSON Pointer `/address/housenumber` that indicates which value has the wrong type.
## Version history
- Added in version 3.10.0.

View File

@@ -0,0 +1,28 @@
# JSON_HAS_CPP_11, JSON_HAS_CPP_14, JSON_HAS_CPP_17, JSON_HAS_CPP_20
```cpp
#define JSON_HAS_CPP_11
#define JSON_HAS_CPP_14
#define JSON_HAS_CPP_17
#define JSON_HAS_CPP_20
```
The library targets C++11, but also supports some features introduced in later C++ versions (e.g., `std::string_view`
support for C++17). For these new features, the library implements some preprocessor checks to determine the C++
standard. By defining any of these symbols, the internal check is overridden and the provided C++ version is
unconditionally assumed. This can be helpful for compilers that only implement parts of the standard and would be
detected incorrectly.
## Default definition
The default value is detected based on preprocessor macros such as `#!cpp __cplusplus`, `#!cpp _HAS_CXX17`, or
`#!cpp _MSVC_LANG`.
## Notes
- `#!cpp JSON_HAS_CPP_11` is always defined.
- All macros are undefined outside the library.
## Version history
- Added in version 3.10.5.

View File

@@ -0,0 +1,30 @@
# JSON_HAS_FILESYSTEM / JSON_HAS_EXPERIMENTAL_FILESYSTEM
```cpp
#define JSON_HAS_FILESYSTEM /* value */
#define JSON_HAS_EXPERIMENTAL_FILESYSTEM /* value */
```
When compiling with C++17, the library provides conversions from and to
[`std::filesystem::path`](https://en.cppreference.com/w/cpp/filesystem/path). As compiler support for filesystem is
limited, the library tries to detect whether
[`<filesystem>`/`std::filesystem`](https://en.cppreference.com/w/cpp/header/filesystem) (`JSON_HAS_FILESYSTEM`) or
[`<experimental/filesystem>`/`std::experimental::filesystem`](https://en.cppreference.com/w/cpp/header/experimental/filesystem)
(`JSON_HAS_EXPERIMENTAL_FILESYSTEM`) should be used. To override the built-in check, define `JSON_HAS_FILESYSTEM` or
`JSON_HAS_EXPERIMENTAL_FILESYSTEM` to `1`.
## Default definition
The default value is detected based on the preprocessor macros `#!cpp __cpp_lib_filesystem`,
`#!cpp __cpp_lib_experimental_filesystem`, `#!cpp __has_include(<filesystem>)`, or
`#!cpp __has_include(<experimental/filesystem>)`.
## Notes
- Note that older compilers or older versions of libstd++ also require the library `stdc++fs` to be linked to for
filesystem support.
- Both macros are undefined outside the library.
## Version history
- Added in version 3.10.5.

View File

@@ -0,0 +1,21 @@
# JSON_NO_IO
```cpp
#define JSON_NO_IO
```
When defined, headers `<cstdio>`, `<ios>`, `<iosfwd>`, `<istream>`, and `<ostream>` are not included and parse functions
relying on these headers are excluded. This is relevant for environments where these I/O functions are disallowed for
security reasons (e.g., Intel Software Guard Extensions (SGX)).
## Default definition
By default, `#!cpp JSON_NO_IO` is not defined.
```cpp
#undef JSON_NO_IO
```
## Version history
- Added in version 3.10.0.

View File

@@ -0,0 +1,32 @@
# JSON_NOEXCEPTION
```cpp
#define JSON_NOEXCEPTION
```
Exceptions can be switched off by defining the symbol `JSON_NOEXCEPTION`. When defining `JSON_NOEXCEPTION`, `#!cpp try`
is replaced by `#!cpp if (true)`, `#!cpp catch` is replaced by `#!cpp if (false)`, and `#!cpp throw` is replaced by
`#!cpp std::abort()`.
The same effect is achieved by setting the compiler flag `-fno-exceptions`.
## Default definition
By default, the macro is not defined.
```cpp
#undef JSON_NOEXCEPTION
```
## Notes
The explanatory [`what()`](https://en.cppreference.com/w/cpp/error/exception/what) string of exceptions is not
available for MSVC if exceptions are disabled, see [#2824](https://github.com/nlohmann/json/discussions/2824).
## See also
- [Switch off exceptions](../../home/exceptions.md#switch-off-exceptions) for more information how to switch off exceptions
## Version history
Added in version 2.1.0.

View File

@@ -0,0 +1,37 @@
# JSON_SKIP_LIBRARY_VERSION_CHECK
```cpp
#define JSON_SKIP_LIBRARY_VERSION_CHECK
```
When defined, the library will not create a compiler warning when a different version of the library was already
included.
## Default definition
By default, the macro is not defined.
```cpp
#undef JSON_SKIP_LIBRARY_VERSION_CHECK
```
## Notes
!!! danger "ABI compatibility"
Mixing different library versions in the same code can be a problem as the different versions may not be ABI
compatible.
## Examples
!!! example
The following warning will be shown in case a different version of the library was already included:
```
Already included a different version of the library!
```
## Version history
Added in version 3.11.0.

View File

@@ -0,0 +1,20 @@
# JSON_SKIP_UNSUPPORTED_COMPILER_CHECK
```cpp
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK
```
When defined, the library will not create a compile error when a known unsupported compiler is detected. This allows to
use the library with compilers that do not fully support C++11 and may only work if unsupported features are not used.
## Default definition
By default, the macro is not defined.
```cpp
#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK
```
## Version history
Added in version 3.2.0.

View File

@@ -0,0 +1,75 @@
# JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER
```cpp
// (1)
#define JSON_CATCH_USER(exception) /* value */
// (2)
#define JSON_THROW_USER(exception) /* value */
// (3)
#define JSON_TRY_USER /* value */
```
Controls how exceptions are handled by the library.
1. This macro overrides [`#!cpp catch`](https://en.cppreference.com/w/cpp/language/try_catch) calls inside the library.
The argument is the type of the exception to catch. As of version 3.8.0, the library only catches `std::out_of_range`
exceptions internally to rethrow them as [`json::out_of_range`](../../home/exceptions.md#out-of-range) exceptions.
The macro is always followed by a scope.
2. This macro overrides `#!cpp throw` calls inside the library. The argument is the exception to be thrown. Note that
`JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield
undefined behavior.
3. This macro overrides `#!cpp try` calls inside the library. It has no arguments and is always followed by a scope.
## Parameters
`exception` (in)
: an exception type
## Default definition
By default, the macros map to their respective C++ keywords:
```cpp
#define JSON_CATCH_USER(exception) catch(exception)
#define JSON_THROW_USER(exception) throw exception
#define JSON_TRY_USER try
```
When exceptions are switched off, the `#!cpp try` block is executed unconditionally, and throwing exceptions is
replaced by calling [`std::abort`](https://en.cppreference.com/w/cpp/utility/program/abort) to make reaching the
`#!cpp throw` branch abort the process.
```cpp
#define JSON_THROW_USER(exception) std::abort()
#define JSON_TRY_USER if (true)
#define JSON_CATCH_USER(exception) if (false)
```
## Examples
??? example
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
```cpp
#include <iostream>
#define JSON_TRY_USER if(true)
#define JSON_CATCH_USER(exception) if(false)
#define JSON_THROW_USER(exception) \
{std::clog << "Error in " << __FILE__ << ":" << __LINE__ \
<< " (function " << __FUNCTION__ << ") - " \
<< (exception).what() << std::endl; \
std::abort();}
#include <nlohmann/json.hpp>
```
## See also
- [Switch off exceptions](../../home/exceptions.md#switch-off-exceptions) for more information how to switch off exceptions
- [JSON_NOEXCEPTION](JSON_NOEXCEPTION) - switch off exceptions
## Version history
- Added in version 3.1.0.

View File

@@ -0,0 +1,56 @@
# JSON_USE_IMPLICIT_CONVERSIONS
```cpp
#define JSON_USE_IMPLICIT_CONVERSIONS /* value */
```
When defined to `0`, implicit conversions are switched off. By default, implicit conversions are switched on. The
value directly affects [`operator ValueType`](../basic_json/operator_ValueType.md).
Implicit conversions can also be controlled with the CMake option `JSON_ImplicitConversions` (`ON` by default) which
sets `JSON_USE_IMPLICIT_CONVERSIONS` accordingly.
## Default definition
By default, implicit conversions are enabled.
```cpp
#define JSON_USE_IMPLICIT_CONVERSIONS 1
```
## Notes
!!! info "Future behavior change"
Implicit conversions will be switched off by default in the next major release of the library.
You can prepare existing code by already defining `JSON_USE_IMPLICIT_CONVERSIONS` to `0` and replace any implicit
conversions with calls to [`get`](../basic_json/get.md).
## Examples
??? example
This is an example for an implicit conversion:
```cpp
json j = "Hello, world!";
std::string s = j;
```
When `JSON_USE_IMPLICIT_CONVERSIONS` is defined to `0`, the code above does no longer compile. Instead, it must be
written like this:
```cpp
json j = "Hello, world!";
auto s = j.get<std::string>();
```
## See also
- [**operator ValueType**](../basic_json/operator_ValueType.md) - get a value (implicit)
- [**get**](../basic_json/get.md) - get a value (explicit)
## Version history
- Added in version 3.9.0.

View File

@@ -0,0 +1,124 @@
# NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT
```cpp
#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...) // (1)
#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)
```
These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as
serialization and want to use the member variable names as object keys in that object. The macro is to be defined
**inside** the class/struct to create code for.
Unlike [`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`](nlohmann_define_type_non_intrusive.md), it can access private members.
The first parameter is the name of the class/struct, and all remaining parameters name the members.
1. Will use [`at`](../basic_json/at.md) during deserialization and will throw
[`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if a key is missing in the JSON object.
2. Will use [`value`](../basic_json/value.md) during deserialization and fall back to the default value for the
respective type of the member variable if a key in the JSON object is missing. The generated `from_json()` function
default constructs an object and uses its values as the defaults when calling the `value` function.
## Parameters
`type` (in)
: name of the type (class, struct) to serialize/deserialize
`member` (in)
: name of the member variable to serialize/deserialize; up to 64 members can be given as comma-separated list
## Default definition
The macros add two friend functions to the class which take care of the serialization and deserialization:
```cpp
friend void to_json(nlohmann::json&, const type&);
friend void from_json(const nlohmann::json&, type&);
```
See examples below for the concrete generated code.
## Notes
!!! info "Prerequisites"
1. The type `type` must be default constructible. See [How can I use `get()` for non-default constructible/non-copyable types?](../../features/arbitrary_types.md#how-can-i-use-get-for-non-default-constructiblenon-copyable-types)
for how to overcome this limitation.
2. The macro must be used inside the type (class/struct).
!!! warning "Implementation limits"
- The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types
with more than 64 member variables, you need to define the `to_json`/`from_json` functions manually.
- The macros only work for the [`nlohmann::json`](../json.md) type; other specializations such as
[`nlohmann::ordered_json`](../ordered_json.md) are currently unsupported.
## Examples
??? example "Example (1): NLOHMANN_DEFINE_TYPE_INTRUSIVE"
Consider the following complete example:
```cpp hl_lines="21"
--8<-- "examples/nlohmann_define_type_intrusive_macro.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_define_type_intrusive_macro.output"
```
Notes:
- `ns::person` is default-constructible. This is a requirement for using the macro.
- `ns::person` has private member variables. This makes `NLOHMANN_DEFINE_TYPE_INTRUSIVE` applicable, but not
`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE`.
- The macro `NLOHMANN_DEFINE_TYPE_INTRUSIVE` is used _inside_ the class.
- A missing key "age" in the deserialization yields an exception. To fall back to the default value,
`NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` can be used.
The macro is equivalent to:
```cpp hl_lines="21 22 23 24 25 26 27 28 29 30 31 32 33"
--8<-- "examples/nlohmann_define_type_intrusive_explicit.cpp"
```
??? example "Example (2): NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT"
Consider the following complete example:
```cpp hl_lines="21"
--8<-- "examples/nlohmann_define_type_intrusive_with_default_macro.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_define_type_intrusive_with_default_macro.output"
```
Notes:
- `ns::person` is default-constructible. This is a requirement for using the macro.
- `ns::person` has private member variables. This makes `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` applicable,
but not `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT`.
- The macro `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` is used _inside_ the class.
- A missing key "age" in the deserialization does not yield an exception. Instead, the default value `-1` is used.
The macro is equivalent to:
```cpp hl_lines="21 22 23 24 25 26 27 28 29 30 31 32 33 34"
--8<-- "examples/nlohmann_define_type_intrusive_with_default_explicit.cpp"
```
Note how a default-initialized `person` object is used in the `from_json` to fill missing values.
## See also
- [NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE / NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT](nlohmann_define_type_non_intrusive.md)
for a similar macro that can be defined _outside_ the type.
- [Arbitrary Types Conversions](../../features/arbitrary_types.md) for an overview.
## Version history
1. Added in version 3.9.0.
2. Added in version 3.11.0.

View File

@@ -0,0 +1,124 @@
# NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT
```cpp
#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(type, member...) // (1)
#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(type, member...) // (2)
```
These macros can be used to simplify the serialization/deserialization of types if you want to use a JSON object as
serialization and want to use the member variable names as object keys in that object. The macro is to be defined
**outside** the class/struct to create code for, but **inside** its namespace.
Unlike [`NLOHMANN_DEFINE_TYPE_INTRUSIVE`](nlohmann_define_type_intrusive.md), it **cannot** access private members.
The first parameter is the name of the class/struct, and all remaining parameters name the members.
1. Will use [`at`](../basic_json/at.md) during deserialization and will throw
[`out_of_range.403`](../../home/exceptions.md#jsonexceptionout_of_range403) if a key is missing in the JSON object.
2. Will use [`value`](../basic_json/value.md) during deserialization and fall back to the default value for the
respective type of the member variable if a key in the JSON object is missing. The generated `from_json()` function
default constructs an object and uses its values as the defaults when calling the `value` function.
## Parameters
`type` (in)
: name of the type (class, struct) to serialize/deserialize
`member` (in)
: name of the (public) member variable to serialize/deserialize; up to 64 members can be given as comma-separated list
## Default definition
The macros add two functions to the namespace which take care of the serialization and deserialization:
```cpp
void to_json(nlohmann::json&, const type&);
void from_json(const nlohmann::json&, type&);
```
See examples below for the concrete generated code.
## Notes
!!! info "Prerequisites"
1. The type `type` must be default constructible. See [How can I use `get()` for non-default constructible/non-copyable types?](../../features/arbitrary_types.md#how-can-i-use-get-for-non-default-constructiblenon-copyable-types)
for how to overcome this limitation.
2. The macro must be used outside the type (class/struct).
3. The passed members must be public.
!!! warning "Implementation limits"
- The current implementation is limited to at most 64 member variables. If you want to serialize/deserialize types
with more than 64 member variables, you need to define the `to_json`/`from_json` functions manually.
- The macros only work for the [`nlohmann::json`](../json.md) type; other specializations such as
[`nlohmann::ordered_json`](../ordered_json.md) are currently unsupported.
## Examples
??? example "Example (1): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE"
Consider the following complete example:
```cpp hl_lines="15"
--8<-- "examples/nlohmann_define_type_non_intrusive_macro.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_define_type_non_intrusive_macro.output"
```
Notes:
- `ns::person` is default-constructible. This is a requirement for using the macro.
- `ns::person` has only public member variables. This makes `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE` applicable.
- The macro `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE` is used _outside_ the class, but _inside_ its namespace `ns`.
- A missing key "age" in the deserialization yields an exception. To fall back to the default value,
`NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT` can be used.
The macro is equivalent to:
```cpp hl_lines="15 16 17 18 19 20 21 22 23 24 25 26 27"
--8<-- "examples/nlohmann_define_type_non_intrusive_explicit.cpp"
```
??? example "Example (2): NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT"
Consider the following complete example:
```cpp hl_lines="20"
--8<-- "examples/nlohmann_define_type_non_intrusive_with_default_macro.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_define_type_non_intrusive_with_default_macro.output"
```
Notes:
- `ns::person` is default-constructible. This is a requirement for using the macro.
- `ns::person` has only public member variables. This makes `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT`
applicable.
- The macro `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT` is used _outside_ the class, but _inside_ its namespace `ns`.
- A missing key "age" in the deserialization does not yield an exception. Instead, the default value `-1` is used.
The macro is equivalent to:
```cpp hl_lines="20 21 22 23 24 25 26 27 28 29 30 31 32 33"
--8<-- "examples/nlohmann_define_type_non_intrusive_with_default_explicit.cpp"
```
Note how a default-initialized `person` object is used in the `from_json` to fill missing values.
## See also
- [NLOHMANN_DEFINE_TYPE_INTRUSIVE / NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT](nlohmann_define_type_intrusive.md)
for a similar macro that can be defined _inside_ the type.
- [Arbitrary Types Conversions](../../features/arbitrary_types.md) for an overview.
## Version history
1. Added in version 3.9.0.
2. Added in version 3.11.0.

View File

@@ -0,0 +1,84 @@
# NLOHMANN_JSON_SERIALIZE_ENUM
```cpp
#define NLOHMANN_JSON_SERIALIZE_ENUM(type, conversion...)
```
By 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.
The `NLOHMANN_JSON_SERIALIZE_ENUM` allows to define a user-defined serialization for every enumerator.
## Parameters
`type` (in)
: name of the enum to serialize/deserialize
`conversion` (in)
: a pair of an enumerator and a JSON serialization; arbitrary pairs can can be given as comma-separated list
## Default definition
The macros add two friend functions to the class which take care of the serialization and deserialization:
```cpp
template<typename BasicJsonType>
inline void to_json(BasicJsonType& j, const type& e);
template<typename BasicJsonType>
inline void from_json(const BasicJsonType& j, type& e);
```
## Notes
!!! info "Prerequisites"
The macro must be used inside the namespace of the enum.
!!! important "Important notes"
- When using [`get<ENUM_TYPE>()`](../basic_json/get.md), undefined JSON values will default to the first specified
conversion. Select this default pair carefully. See example 1 below.
- If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the
list will be returned when converting to or from JSON. See example 2 below.
## Examples
??? example "Example 1: Basic usage"
The example shows how `NLOHMANN_JSON_SERIALIZE_ENUM` can be used to serialize/deserialize both classical enums and
C++11 enum classes:
```cpp hl_lines="16 17 18 19 20 21 22 29 30 31 32 33"
--8<-- "examples/nlohmann_json_serialize_enum.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_json_serialize_enum.output"
```
??? example "Example 2: Multiple conversions for one enumerator"
The example shows how to use multiple conversions for a single enumerator. In the example, `Color::red` will always
be *serialized* to `"red"`, because the first occurring conversion. The second conversion, however, offers an
alternative *deserialization* from `"rot"` to `Color::red`.
```cpp hl_lines="17"
--8<-- "examples/nlohmann_json_serialize_enum_2.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_json_serialize_enum_2.output"
```
## See also
- [Specializing enum conversion](../../features/enum_conversion.md)
## Version history
Added in version 3.4.0.

View File

@@ -0,0 +1,23 @@
# NLOHMANN_JSON_VERSION_MAJOR, NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH
```cpp
#define NLOHMANN_JSON_VERSION_MAJOR /* value */
#define NLOHMANN_JSON_VERSION_MINOR /* value */
#define NLOHMANN_JSON_VERSION_PATCH /* value */
```
These macros are defined by the library and contain the version numbers according to
[Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html).
## Default definition
The macros are defined according to the current library version.
## See also
- [meta](../basic_json/meta.md) - returns version information on the library
- [JSON_SKIP_LIBRARY_VERSION_CHECK](json_skip_library_version_check.md) - skip library version check
## Version history
- Added in version 3.1.0.