4

我有这段代码将一些成员添加到对象类型文档

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());
}

和这件作品来序列化它

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

但得到的价值是

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

有人知道为什么吗?

4

3 回答 3

2

如果您想要一个变量字符串作为 addmember 函数中的成员名称,以下对我有用:

    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
于 2015-01-14T20:09:14.823 回答
1

根据 vaultah 的建议,我发现我必须明确创建

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

强制它使用字符串复制构造函数,并使用

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

添加到 json 文档。

于 2014-11-30T14:00:43.580 回答
0
rapidjson::Document json;
json.setObject();
json.AddMemeber(StringRef(TEST01.c_str()), Value(123), json.GetAllocator());

那么,为什么“test02”和“test03”是mojibake,这是因为内存分配不正确。
虽然c_str()是弱引用,所以上面的代码可以工作,但不好。

于 2016-04-19T12:45:09.887 回答