Tencent / rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API
http://rapidjson.org/
Other
14k stars 3.5k forks source link

need help with copying text strings (not just reference them) #2275

Open u1550l opened 2 months ago

u1550l commented 2 months ago

I have problems with assigning strings to a document. Obviously this is caused by the copy/link mechanism.

my code: (note: to keep the code snippet small, I removed all return value checks)

rapidjson::Document myDoc;
rapidjson::Value objValue;

setJsonHeader(std::string &jsonstr)
{
   rapidjson::Document d;
   //>>> this would work: >>> static rapidjson::Document d;

   d.SetObject();
   d.Parse(jsonstr.c_str());

   objValue.SetObject();
   objValue.AddMember("rpc", d["header"]["rpc"], myDoc.GetAllocator());
   objValue.AddMember("uid", d["header"]["uid"], myDoc.GetAllocator());

   myDoc.RemoveAllMembers();
   myDoc.AddMember("header", objValue, myDoc.GetAllocator());
}

before calling the function, jsonstr contains:

{
    "header": {
        "rpc": "hereIsSomeTextString",
        "uid": 42
    },
    ...
}

inside setJsonHeader(), all behaves as expected. But after calling function setJsonHeader(), myDoc looks like this:

{
    "header": {
        "rpc": " \u0015\u0001¦¦¦\u0000\u0000omeTextString",
        "uid": 42
    }
}

the string is not valid any more.

My current workaround: use the "static" declaration of ["d"](rapidjson::Document d) but then the function is no more re-entrant.

My question: how can I force rapidjson to actualy copy the contents (i.e. std:strings) instead of just linking them?