Serializing

Serialization is the process where a JSON document represented in memory by a value is turned into a sequence of characters. The library provides the following free functions and types for serialization:

Table 5. Serialization Functions and Types
Name Description

operator<<

Serialize a value, array, object, or string to a std::ostream.

serialize

Return a std::string representing a serialized value, array, object, or string.

serializer

A stateful object which may be used to efficiently serialize one or more instances of value, array, object, or string.

To facilitate debugging and ease of output, library container types may be written to standard output streams using the stream operator:

value jv = { 1, 2, 3, 4, 5 };

std::cout << jv << "\n";

The serialize function converts a value into a std::string:

value jv = { 1, 2, 3, 4, 5 };

std::string s = serialize( jv );

In situations where serializing a value in its entirety is inefficient or even impossible, serializer can be used to serialize a value incrementally. This may be done for a variety of reasons, such as to avoid buffering the entire output, or to ensure that a fixed amount of work is performed in each cycle. Instances of serializer maintain an output state using internal dynamically allocated structures, with an interface to retrieve successive buffers of the serialized output into a caller provided buffer. Here is an example, demonstrating how operator<< may be implemented using a serializer:

// Serialize a value into an output stream

std::ostream&
operator<<( std::ostream& os, value const& jv )
{
    // Create a serializer
    serializer sr( get_stream_flags(os) );

    // Set the serializer up for our value
    sr.reset( &jv );

    // Loop until all output is produced.
    while( ! sr.done() )
    {
        // Use a local buffer to avoid allocation.
        char buf[ BOOST_JSON_STACK_BUFFER_SIZE ];

        // Fill our buffer with serialized characters and write it to the output stream.
        os << sr.read( buf );
    }

    return os;
}

As with the parser, the serializer may be reused by calling serializer::reset. This sets up the object to serialize a new instance and retains previously allocated memory. This can result in performance improvements when multiple variables are serialized.