Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Tutorials

Serialization
Incremental Processing
Push Parser
[Note] Note

The tutorials assume that the following alias has been declared

namespace json = trial::protocol::json;

This tutorial shows how the JSON output archive and the JSON input archive can be used to serialize C++ data into JSON and deserialize JSON into C++ data in just a few lines of code.

Fundamental types

We start by serializing fundamental types, because there is built-in serialization support for most of them.

The JSON output archive knows how to generate valid JSON, but it needs a buffer to store the output in. This buffer is passed to the constructor of the output archive. We can choose between several buffer types. In the following we will only demonstrate how to serialize to a std::string. We first need to include a wrapper for std::string that is used by the output archive.

#include <trial/protocol/buffer/string.hpp> // Use std::string as output buffer

We also need to include json::oarchive together with other headers to glue Trial.Protocol into Boost.Serialization. This is most easily done like this:

#include <trial/protocol/json/serialization.hpp>

Serializing is as simple as creating a std::string and a json::oarchive, and then stream our data to the archive.

// Create data
bool input = true;

// Serialization
std::string buffer;
json::oarchive oarchive(buffer);
oarchive << input;

The buffer string now contains the formatted JSON output.

assert(buffer == "true");

We can deserialize the buffer again with the JSON input archive.

bool output = false;
json::iarchive iarchive(buffer);
iarchive >> output;

assert(output == true);

Containers

There is also built-in support for serialization of certain standard C++ containers, such as std::vector, std::set, and std::map.

The following example shows how to serialize an std::map. The serialization code follows the same pattern as used in the previous example.

#include <trial/protocol/buffer/string.hpp>
#include <trial/protocol/json/serialization.hpp>

// Build data
std::map<std::string, std::string> input;
input["alpha"] = "hydrogen";
input["bravo"] = "helium";

// Serialization
std::string buffer;
json::oarchive oarchive(buffer);
oarchive << input;

assert(buffer == "{\"alpha\":\"hydrogen",\"bravo\":\"helium\"}");

Deserialization is done by adding:

std::map<std::string, std::string> output;
json::iarchive iarchive(buffer);
iarchive >> output;

assert(output.size() == 2);
assert(output["alpha"] == "hydrogen");
assert(output["bravo"] == "helium");


PrevUpHomeNext