Back to the table of contents

Previous      Next

Serialization

In order to write code that will serialize and deserialize your models, you will use the GDom and GDomNode classes (see the API documentation). These classes enable you to build a document object model (DOM) that can be serialized to a variety of formats, such as JSON, XML, or BLOb.

Why not just serialize/deserialize your model directly? There are several advantages to using a DOM. Most significantly, it is very easy to build a DOM, and to use one. So, this reduces the burden on the developer. Another advantage is that you can serialize to the format of your choice without having to write special code for it. So, all you need to do is write a method that will convert your model to the DOM, and you can decide later what format to use for serialization.

For example, suppose you have a class like this:

	class MyClass
	{
		string m_name;
		int m_age;
		double m_height;
		bool m_admin;
		vector<string> m_friends;
	};
Here is some code that will marshall this object into a DOM:
	GDomNode* MyClass::serialize(GDom* pDoc)
	{
		GDomNode* pNode = pDoc->newObj();
		pNode->add(pDoc, "name", m_name.c_str());
		pNode->add(pDoc, "age", m_age);
		pNode->add(pDoc, "height", (long long)m_height);
		pNode->add(pDoc, "admin", m_admin);
		GDomNode* pFriends = pNode->add(pDoc, "friends", pDoc->newList());
		for(size_t i = 0; i < m_friends.size(); i++)
			pFriends->add(pDoc, m_friends[i].c_str());
		return pNode;
	}
This code will create a DOM with a structure like this:

Here is a JSON encoding of this DOM:
		{
			"name":"bob",
			"age":21
			"height":5.9
			"admin":false
			"friends":[
				"al",
				"charlie",
				"dave"
			]
		}

By design, each node in the DOM may have child nodes, or it may contain a value, but not both. This forms a natural separation between data (in the leaf nodes) and meta-data (represented by the interior nodes). Since it is bad practice to stuff data values into interior nodes in a DOM anyway, this is a good limitation.

Next, let's write some code that will unmarshall the object from the DOM

	void MyClass::MyClass(GDomNode* pNode)
	{
		m_name = pNode->getString("name");
		m_age = pNode->getInt("age");
		m_height = pNode->getDouble("height");
		m_admin = pNode->getBool("admin");
		for(GDomListIterator li(pNode->field("friends")); li.current(); li.advance())
			m_friends.push_back(li.currentString());
	}

Previous      Next

Back to the table of contents