How to create and serialize a document in RapidJSON

RapidJSON is a JSON library optimized for speed - hence it lacks some convieniece and lacks easy-to-use documentation on how to create JSON documents from scratch.

Here’s how you can create a Document:

// Generate document: {"text": "Hello JSON!"}
Document doc;
doc.SetObject(); // Make doc an object !
doc.AddMember("text", "Hello JSON!", doc.GetAllocator());

Full example, which prints to cout:

#include <iostream>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/ostreamwrapper.h>
using namespace rapidjson;
using namespace std;

int main() {
    // Generate document: {"text": "Hello JSON!"}
    Document doc;
    doc.SetObject(); // Make doc an object !
    doc.AddMember("text", "Hello JSON!", doc.GetAllocator());
    // Write to stdout
    OStreamWrapper out(cout);
    Writer<OStreamWrapper> writer(out);
    doc.Accept(writer);
}