Emergent Design Emergent Design Atom Github

Entity serialisation

25 July 2013

In languages such as C#, serialising an object is reasonably trivial thanks to reflection. This means that there are a wide selection of libraries that deal with a variety of serialisation formats (JSON, XML, YAML etc.).

However, due to the lack of reflection, the options in C++ are somewhat limited.

Some libraries require a precompilation step. Whilst others represent the entities in an intermediate form and provide an API such as DOM to access the properties.

Boost does actually provide a library capable of serialising to and from object instances, but we found the syntax a little messy and had issues with the JSON parser not working properly (when using the stable libraries in the Ubuntu package repositories).

Presenting libentity

Our library aims to provide serialisation of objects with very little boilerplate code and uses an intermediate tree structure to simplify the task of writing emitters and parsers.

It started life as a side project to develop an easy to use tree that could replace an existing solution in our codebase, but we soon realised that certain C++11 features would allow us to implement an entity mapper.

An example

Taken straight from the project readme:

#include <iostream>
#include <entity/entity.hpp>
#include <entity/json.hpp>

using namespace std;
using namespace ent;

// A structure with simple members, derived from entity
struct Simple : entity
	string name	= "default";
	bool flag	= false;
	int integer = 0;

	mapping describe()
		return { eref(name), eref(flag), eref("int", integer) };

const string JSON_TEXT = u8R"json(
		"name": "simple",
		"flag": true,
		"int":  42

int main(int argc, char *argv[])
	Simple simple;

	// Serialise the simple object to JSON (will contain the default
	// values assigned above)
	cout << entity::encode<json>(simple) << endl;

	// Deserialise the simple object from a JSON string
	simple = entity::decode<json>(JSON_TEXT);

	// These values will now match those defined in JSON_TEXT
	cout << "Name    = " << simple.name << endl;
	cout << "Flag    = " << simple.flag << endl;
	cout << "Integer = " << simple.integer << endl;

	return 0;

It can support complex object trees provided that vectors are used for arrays and any child objects are also derived from entity.

Credit where it’s due