In this library the types <<ref_array>>, <<ref_object>>, and <<ref_string>> hold JSON arrays, objects, and strings respectively while the type <<ref_value>> is a special variant which can hold any JSON element. Here we construct an empty object and then insert the elements above:
While keys are strings, the mapped type of objects and the element type of arrays is the aforementioned type <<ref_value>> which can hold any JSON element, as seen in the previous assignments. Instead of building the JSON document using a series of function calls, we can build it in one statement using an initializer list:
When a <<ref_value>>, <<ref_array>>, or <<ref_object>> is assigned or constructed from an initializer list, the creation of the new value happens only once. This makes initializer lists equally efficient as using the other ways to create a value. The types in this library are first-class, supporting copy and move construction and assignment:
To permit custom memory allocation strategies, these containers all allow construction with a <<ref_storage_ptr>> which is a smart pointer to a {ref_memory_resource}. The constructor signatures have the same ordering as their `std` equivalents which use {req_Allocator} parameters. Once a container is constructed its memory resource can never change. Here we create an array without performing any dynamic allocations:
Up until now we have shown how values may be constructed from a memory resource pointer, where ownership is not transferred. In this case the caller is responsible for ensuring that the lifetime of the resource is extended for the life of the container. Sometimes you want the container to acquire shared ownership of the resource. This is accomplished with <<ref_make_shared_resource>>:
We can define a conversion from the user-defined type to a <<ref_value>> by defining an overload of `tag_invoke` in the same namespace. This maps `customer` to a JSON object:
To go from JSON to a user-defined type we use <<ref_value_to>>, which uses another overload of `tag_invoke`. This converts a JSON value to a `customer`. It throws an exception if the contents of the value do not match what is expected:
The library's generic algorithms recognize when you are converting a <<ref_value>> to a container which resembles an array or object, so if you wanted to turn a JSON array into a vector of customers you might write: