Understanding RapidJson — Part 2
In my previous blog on Rapidjson, alot of people asked for a detailed example in the comments so here is part 2 of Understanding Rapidjson with a slightly detailed example. I hope this will help you all.
We will straightaway improve on my last example in the previous blog and modify the changeDom function to add more complex object to the DOM tree.
template <typename Document>
void changeDom(Document& d){
Value& node = d[“hello”];
node.SetString(“c++”);
Document subdoc(&d.GetAllocator());
subdoc.SetObject(); // starting the object
Value arr(kArrayType); // the innermost array
Value::AllocatorType allocator;
for (unsigned i = 0; i < 10; i++)
arr.PushBack(i, allocator); // adding values to array , this function expects an allocator object
// adding the array to its parent object and so on , finally adding it to the parent doc object
subdoc.AddMember(“New”, Value(kObjectType).Move().AddMember(“Numbers”,arr, allocator), subdoc.GetAllocator());
d.AddMember(“testing”,subdoc, d.GetAllocator()); // finally adding the sub document to the main doc object
d[“f”] = true;
d[“t”].SetBool(false);
}
Here we are creating Value objects of type kArrayType and kObjectType and appending them to their parent node from innermost to outermost.
Before Manupulation
{
"hello": "world",
"t": true,
"f": false,
"n": null,
"i": 123,
"pi": 3.1416,
"a": [
0,
1,
2,
3
]
}
After Manupulation
{
"hello": "c++",
"t": false,
"f": true,
"n": null,
"i": 123,
"pi": 3.1416,
"a": [
0,
1,
2,
3
],
"testing": {
"New": {
"Numbers": [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
]
}
}
}
The above changeDom can also be written using prettywritter object as follows:
template <typename Document>
void changeDom(Document& d){
Value& node = d[“hello”];
node.SetString(“c++”);
Document subdoc(&d.GetAllocator()); // sub-document
// old school write the json element by element
StringBuffer s;
PrettyWriter<StringBuffer> writer(s);
writer.StartObject();
writer.String(“New”);
writer.StartObject();
writer.String(“Numbers”);
writer.StartArray();
for (unsigned i = 0; i < 10; i++)
writer.Uint(i);
writer.EndArray();
writer.EndObject();
writer.EndObject();
subdoc.Parse(s.GetString()); // Parsing the string written to buffer to form a sub DOM
d.AddMember(“testing”,subdoc, d.GetAllocator()); // Attaching the Sub DOM to the Main DOM object
d["f"] = true;
d["t"].SetBool(false);
}
Happy Coding! Cheers.
More reads:
https://stackoverflow.com/questions/32896695/rapidjson-add-external-sub-document-to-document