A recent project of mine necessitated that I find a way to share data between a client application written in C++ and a host application written in C#. After talking with the other programmer on the project,we decided that usingJson to share data between the applications would be the best solution. This sent me on a search for a decent API for parsingJson data,which led toJsonCpp.
A cursory glance led me to conclude that this API would likely provide me with everything I would need for object serialization. The problem,however,was coming up with a decent design that would allow for full featured serialization. The goals were simple. I needed to be able to serialize and deserialze a class. I would also need access to all data members,including primitives,data structures,and nested classes.
JsonCpp provides us with the capability to do this with relative ease. As such,I hope to provide you all with a basic design to accomplish this. Luckily,we won’t need a deep understanding of JsonCpp to accomplish our goals. As such,I’m not going to overly explain much of the JsonCpp concepts,as the JsonCpp documentation is a good enough resource.
First,let’s consider a simple test class.
1
2
3
4
5
6
7
8
9
10
11
12
|
class
TestClassA
{
public
:
TestClassA(
void
);
virtual
~TestClassA(
void
);
private
:
int
m_nTestInt;
double
m_fTestFloat;
std::string m_TestString;
bool
m_bTestBool;
};
|
This class should provide us with a basic framework to test serialization. We’re going to start with primitive data first (granted,std::string isn’t strictly primitive,but it’s primitive enough).
Now that we have a basic test case,lets design a basic interface that all of our serializable classes can inherit from.
1
2
3
4
5
6
7
|
class
IJsonSerializable
{
public
:
virtual
~IJsonSerializable(
void
) {};
virtual
void
Serialize( Json::Value& root ) =0;
virtual
void
Deserialize( Json::Value& root) =0;
};
|
This should be self explanitory. We obvIoUsly need to includejson.h in order to have access to theJson::Value class. The Json::Value class is actually fairly complex,and as such we aren’t going to spent much time examining it. Suffice to say,we are going to treat it as a sort of map,mapping our Metadata tags to the actual values we will be serializing. This will make much more sense once we work on the implementation of the Serialize() and Deserialize() methods in our classes.
So let’s update our updated test class definition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class
TestClassA :
public
IJsonSerializable
{
public
:
TestClassA(
void
);
virtual
~TestClassA(
void
);
virtual
void
Serialize( Json::Value& root );
virtual
void
Deserialize( Json::Value& root);
private
:
int
m_nTestInt;
double
m_fTestFloat;
std::string m_TestString;
bool
m_bTestBool;
};
|
Now before we progress further on the C++ side of things,let’s cook up some testJson data to work with.
1
2
3
4
5
6
|
{
"testboolA"
:
true
,
"testfloatA"
:
3.14159
,
"testintA"
:
42
,
"teststringA"
:
"foo"
}
|
Whether you knowJson or not,this data structure should be completely self-explanatory. The goal here is going to be to deserialize this data into our class. However,we have one more thing to do.
The last class we need to design here is the actual serializer class.
1
2
3
4
5
6
7
8
9
|
class
CJsonSerializer
{
public
:
static
bool
Serialize( IJsonSerializable* pObj,std::string& output );
static
bool
Deserialize( IJsonSerializable* pObj,std::string& input );
private
:
CJsonSerializer(
void
) {};
};
|
This is a simple little “static class”. We’ll make the constructor private this way we can’t actually instantiate it. We will simply deal with the methods directly. This will let us add a second layer of abstraction to JsonCpp.
Alright,our basic design is done. Let’s get into the implementation. Let’s start with our test class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
void
TestClassA::Serialize( Json::Value& root )
{
// serialize primitives
root[
"testintA"
] = m_nTestInt;
root[
"testfloatA"
] = m_fTestFloat;
root[
"teststringA"
] = m_TestString;
root[
"testboolA"
] = m_bTestBool;
}
void
TestClassA::Deserialize( Json::Value& root )
{
// deserialize primitives
m_nTestInt = root.get(
"testintA"
,0).asInt();
m_fTestFloat = root.get(
"testfloatA"
,0.0).asDouble();
m_TestString = root.get(
"teststringA"
,
""
).asString();
m_bTestBool = root.get(
"testboolA"
,
false
).asBool();
}
|
Remember when I said we were going to look at theJson::Value class like a map? That should make more sense now. The Serialize() method should make sense. We are simply adding the values to our root object as if it was a map. The keys we are using map directly to the Metadata in theJson data. The Deserialize() method is only slightly more complex. We need to use the get() method in order to retrieve our data. The get() method takes two parameters: get( <key>,<defaultvalue>). Knowing that,the method should make sense. We simply call get() with each key and place the values from theJson into our members.
Now let’s move on to the CJsonSerializer class implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
bool
CJsonSerializer::Serialize( IJsonSerializable* pObj,std::string& output )
{
if
(pObj == NULL)
return
false
;
Json::Value serializeRoot;
pObj->Serialize(serializeRoot);
Json::StyledWriter writer;
output = writer.write( serializeRoot );
return
true
;
}
bool
CJsonSerializer::Deserialize( IJsonSerializable* pObj,std::string& input )
{
if
(pObj == NULL)
return
false
;
Json::Value deserializeRoot;
Json::Reader reader;
if
( !reader.parse(input,deserializeRoot) )
return
false
;
pObj->Deserialize(deserializeRoot);
return
true
;
}
|
It should be obvIoUs now why we wanted a second level of abstraction from JsonCpp.
Let’s look at the Serialize() method here. We need to pass two parameters,a pointer to the IJsonSerializable object to be serialized,and a reference to a std::string. That string is going to hold the serializedJson data from our class. This is very rudimentary. Wesimply create an instance of aJson::Value object to act as our root,and pass it to the Serialize() method of the object in question. That Serialize() method will fill theJson::Value object with all of the serialized data. We then create an instance ofJson::StyledWriter,and use it to write theJson data to the emptystd::string we originally passed.
As for the Deserialize() method,it’s not terribly different aside from the fact that the std::string we pass is going to contain Json instead of being empty. We will create an instance ofJson::Reader and use it to parse our input string and fill a Json::Value object for us. We will then use that newJson::Value object and pass it to the IJsonSerializable objects Deserialze() method,which will set the data members based on theJson::Value object’s values.
As you can see,this is all pretty simple. We can now create a simple test case.
1
2
3
4
5
6
7
8
9
10
|
TestClassA testClass;
std::string input =
"{ \"testintA\" : 42,\"testfloatA\" : 3.14159,\"teststringA\" : \"foo\",\"testboolA\" : true }\n"
;
CJsonSerializer::Deserialize( &testClass,input );
std::cout <<
"Raw Json Input\n"
<< input <<
"\n\n"
;
std::string output;
CJsonSerializer::Serialize( &testClass,output);
std::cout <<
"testClass Serialized Output\n"
<< output <<
"\n\n\n"
;
|
If everything went according to plan,you should see the following:
1
2
3
4
5
6
7
8
9
10
|
Raw Json Input
{
"testintA"
: 42,
"testfloatA"
: 3.14159,
"teststringA"
:
"foo"
,
"testboolA"
:
true
}
testClass Serialized Output
{
"testboolA"
:
true
,
"testfloatA"
: 3.14159,
"testintA"
: 42,
"teststringA"
:
"foo"
}
|
Essentially our test case simply created an “empty” TestClass object. It then deserialized a string of inputJson data into the class,filling it’s members. We then create a new empty output string,and deserialize our TestClass object into that string. If the outut is what we expect,then we can assume that basic serialization and deserialization is working!
http://www.danielsoltyka.com/programming/2011/04/15/simple-class-serialization-with-jsoncpp/
P.S. complete code:
//#include <cstdlib> //#include <fstream> #include <iostream> #include "json/json.h" class IJsonSerializable { public: virtual ~ IJsonSerializable (void) { }; virtual void Serialize (Json::Value & root) = 0; virtual void Deserialize (Json::Value & root) = 0; }; class TestClassA : public IJsonSerializable { public: TestClassA (); virtual ~ TestClassA (void) { } virtual void Serialize (Json::Value & root); virtual void Deserialize (Json::Value & root); private: int m_nTestInt; double m_fTestFloat; std::string m_TestString; bool m_bTestBool; }; TestClassA::TestClassA() { m_nTestInt = 42; m_fTestFloat = 3.14159; m_TestString = "foo"; m_bTestBool = true; } void TestClassA::Serialize (Json::Value & root) { // serialize primitives root["testintA"] = m_nTestInt; root["testfloatA"] = m_fTestFloat; root["teststringA"] = m_TestString; root["testboolA"] = m_bTestBool; } void TestClassA::Deserialize (Json::Value & root) { // deserialize primitives m_nTestInt = root.get ("testintA",0).asInt (); m_fTestFloat = root.get ("testfloatA",0.0).asDouble (); m_TestString = root.get ("teststringA","").asString (); m_bTestBool = root.get ("testboolA",false).asBool (); } class CJsonSerializer { public: static bool Serialize (IJsonSerializable * pObj,std::string & output); static bool Deserialize (IJsonSerializable * pObj,std::string & input); private: CJsonSerializer (void) { }; }; bool CJsonSerializer::Serialize (IJsonSerializable * pObj,std::string & output) { if (pObj == NULL) return false; Json::Value serializeRoot; pObj->Serialize (serializeRoot); Json::StyledWriter writer; output = writer.write (serializeRoot); return true; } bool CJsonSerializer::Deserialize (IJsonSerializable * pObj,std::string & input) { if (pObj == NULL) return false; Json::Value deserializeRoot; Json::Reader reader; if (!reader.parse (input,deserializeRoot)) return false; pObj->Deserialize (deserializeRoot); return true; } int main (void) { TestClassA testClass; std::string input = "{ \"testintA\" : 42,\"testboolA\" : true }\n"; CJsonSerializer::Deserialize (&testClass,input); std::cout << "Raw Json Input\n" << input << "\n\n"; std::string output; CJsonSerializer::Serialize (&testClass,output); std::cout << "testClass Serialized Output\n" << output << "\n\n\n"; return 0; }