Published:

Serializing directly between C++ objects and Json files

bookmark 1 min read

C++ is a popular Object-oriented language. Json is a popular format for storage of Objects. Why is it so hard to make those two things play ball? Well, actually - it's not. Not any more.

About two years ago I wrote restc-cpp, a REST client library for modern C++. One of it's nice features is that it allows you to serialize C++ objects directly to and from the Json that is sent over the wire to the REST API server.

Yesterday a user of the library asked me if it can also serialize C++ objects to file. So I spent an hour today implementing that. I mean, it is an obvious feature for a library that already know how to serialize between C++ classes and Json!

So, after the todays commit, you can serialize directly between std::istream, C++ objects and std::ostream.

Lets look at some code:

using namespace std;
using namespace restc_cpp;

// Our configuration object
struct Config {
    int max_something = {};
    string name;
    string url;
};

// Declare Config to boost::fusion, so we can serialize it
BOOST_FUSION_ADAPT_STRUCT(
    Config,
    (int, max_something)
    (string, name)
    (string, url)
)

main() {

    // Instatiate the config object
    Config config;

    {
        // Create an istream for the json file
        ifstream ifs("config.json");

        // Read the config file into the config object.
        SerializeFromJson(config, ifs);
    }

    // Do something with config...

    {
        // Create an ostream for the json file
        ofstream ofs("config.json");

        // Serialize Config to the file
        SerializeToJson(config, ofs);
    }
}

Simple, uh?

SerializeFromJson() and SerializeToJson() does all the heavy lifting.

This part of the library is by the way header only. If this is all you intend to do, you don't have to compile the library - just consume the headers.

Full example here: Serializing a file...