Jarle Aase

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:

 1using namespace std;
 2using namespace restc_cpp;
 4// Our configuration object
 5struct Config {
 6    int max_something = {};
 7    string name;
 8    string url;
11// Declare Config to boost::fusion, so we can serialize it
13    Config,
14    (int, max_something)
15    (string, name)
16    (string, url)
19main() {
21    // Instatiate the config object
22    Config config;
24    {
25        // Create an istream for the json file
26        ifstream ifs("config.json");
28        // Read the config file into the config object.
29        SerializeFromJson(config, ifs);
30    }
32    // Do something with config...
34    {
35        // Create an ostream for the json file
36        ofstream ofs("config.json");
38        // Serialize Config to the file
39        SerializeToJson(config, ofs);
40    }

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...