Search code examples
c++c++11rapidjson

Problems with input to a function that used RapidJson its AddMember function


I am trying to write a function that should check whether a member exists on a document. If it does it should remove the member and re-add it with a different value.

This is what I got so far (d is a rapidjson::Document):

void addMemberWithoutDuplication(std::string member, rapidjson::Value val) {
    if (d.HasMember(member)) {
        d.RemoveMember(member);
    }
    d.AddMember(rapidjson::StringRef(member), val, allocator);
}

This compiles and runs however the output is not as expected: enter image description here

As shown rapidjson::StringRef(member) seems to be the cause of the question marks inside the boxes.

Reading these pages of the docs did not help me a lot:

From what I read I should be doing it correctly but most likely my inexperience reading these types of docs is an issue here. Does anyone know what I am doing wrong or am missing?


Solution

  • I eventually found an answer in this post: https://github.com/Tencent/rapidjson/issues/261

    When using a dynamic reference, a copy of the string should be stored in a rapidjson::Value.

    This makes the code as follows:

    void addMemberWithoutDuplication(std::string member, rapidjson::Value val) {
        if (d.HasMember(member)) {
            d.RemoveMember(member);
        }
        rapidjson::Value key(member.c_str(), allocator);
        d.AddMember(key, val, allocator);
    }