rapidjson proper json creation

André Moreira picture André Moreira · Mar 1, 2016 · Viewed 8.8k times · Source

I'm trying to create a json using rapidjson and I am having some unexpected problems with generating a proper output.

I'm creating and populating a document like this:

Document d;
d.SetObject();

rapidjson::Document::AllocatorType& allocator = d.GetAllocator();

size_t sz = allocator.Size();

d.AddMember("version",  1, allocator);
d.AddMember("testId",   2, allocator);
d.AddMember("group",    3, allocator);
d.AddMember("order",    4, allocator);

Value tests(kArrayType);
Value obj(kObjectType);
Value val(kObjectType);

obj.AddMember("id", 1, allocator);

string description = "a description";
val.SetString(description.c_str(), static_cast<SizeType>(description.length()), allocator);
obj.AddMember("description", val, allocator);

string help = "some help";
val.SetString(help.c_str(), static_cast<SizeType>(help.length()), allocator);
obj.AddMember("help", val, allocator);

string workgroup = "a workgroup";
val.SetString(workgroup.c_str(), static_cast<SizeType>(workgroup.length()), allocator);
obj.AddMember("workgroup", val, allocator);

val.SetBool(true);
obj.AddMember("online", val, allocator);

tests.PushBack(obj, allocator);
d.AddMember("tests", tests, allocator);

// Convert JSON document to string
rapidjson::StringBuffer strbuf;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
d.Accept(writer);

When I run this code, I'm expecting to obtain this json:

{
    "version": 1,
    "testId": 2,
    "group": 3,
    "order": 4,
    "tests": [
        {
            "id": 1,
            "description": "a description",
            "help": "some help",
            "workgroup": "a workgroup",
            "online": true
        }
    ]
}

but the actual generated output is...

{
    "version": 1,
    "testId": 2,
    "group": 3,
    "order": 4,
    "tests": [
        {
            "id": 1,
            "description": "a description",
            "help": "some help",
            "workgroup": "a workgroup",
            "online": tr{
    "version": 1,
    "testId": 2,
    "group": 3,
    "order": 4,
    "tests": [
        {
            "id": 1,
            "description": "a description",
            "help": "some help",
            "workgroup": "a workgroup",
            "online": true
        }
    ]
}

Any ideas?

Answer

Andr&#233; Moreira picture André Moreira · Mar 2, 2016

In the end I managed to track the problem down to the way I was outputing the string with OutputDebugString in VS. If I saved the resulting string (given by GetString()), the output was as expected!

Foiled by the debug trap I was!