weird member name string with rapidjson

4.2k Views Asked by At

I have this piece of code which add some members to a Object type Document

void test01(rapidjson::Document& doc)
{
    doc.AddMember("test01", 123, doc.GetAllocator());
    char name[] = "test02";
    doc.AddMember(name, 2, doc.GetAllocator());
    string sname = "test03";
    doc.AddMember(sname.c_str(), 3, doc.GetAllocator());
}

and this piece to serialize it

rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer (buffer);
document.Accept (writer);
std::string json = buffer.GetString();

but the value got was

{
    "test01": 123,
    "ÌÌÌÌÌÌ": 2,
    "ÌÌÌÌÌÌ": 3
}

do anybody know why?

3

There are 3 best solutions below

0
On BEST ANSWER

based on what vaultah suggested, I'd found out that I have to explicitly create

rapidjson::Value name(pair.first.c_str(), allocator);

to force it to use a string-copy constructor, and use

json.AddMember(name.Move(), Value(123).Move(), allocator);

to add to json document.

0
On

If you want a variable string as the member name in the addmember function, the following worked for me:

    char buff[50];
    sprintf(buff, "%d", somefacyNumber);

    Value vMemberName  (kStringType);
    vMemberName.SetString(buff, strlen(buff), nalloc);     // for buffs we must do this, 
       // if we use stringref, then next next time we add a buffer we stamp on previous value


    someObject.AddMember(vMemberName, vSomeOtherValue, nalloc); // nalloc is our allocator
0
On
rapidjson::Document json;
json.setObject();
json.AddMemeber(StringRef(TEST01.c_str()), Value(123), json.GetAllocator());

So, why "test02" and "test03" are mojibake, it's because of the memory isn't allocated in the right way.
While c_str() is weak reference, so, the above code can work, but are not good.