|
DAW JSON Link
|
nullable types are supported by using the json_nullable mapping type or appending the type name with _null to use the convenience wrapper. The requirement of the underlying type is that it will be default constructable for null values or support the Nullable Concept.
Named _null mappings accept a JsonNullable template argument that controls how an empty value is serialized when it is a class member:
JsonNullable::Nullable (the default) permits the entire member to be omitted.JsonNullable::NullVisible always emits the member, using null for an empty value.When a nullable mapping is serialized, its null state is detected in this order:
IsNull type was specified, a default-constructed IsNull is called with the mapped value.bool, false means null.nullable_value_traits<T>::has_value is used for types satisfying the Nullable Concept.The optional IsNull template argument is useful when neither of the default tests represents the type's null state. It is the last argument of both mappings:
For example, a std::variant can reserve std::monostate as its null state:
Here, a variant holding std::monostate serializes as {"member":null}. IsNull controls null detection during serialization; it does not construct a value when parsing JSON null. Parsing continues to use Constructor, and daw::use_default creates a default-constructed variant containing std::monostate.
For a named class member with a custom null test, use JsonNullable::NullVisible as above so the null member is emitted. For an unnamed value, such as an array element or root value, json_nullable_no_name always emits the JSON literal null for a value that passes its null test.
For complete named and unnamed mappings, see json_nullable_is_null_test.cpp.
Take the following JSON
The JSON document is an array of an object with two members, an optional int, a string, and an optional bool.
To see a working example using this code, refer to cookbook_optional_values1_test.cpp.