按索引访问 rapidjson::Document 数组

Accessing rapidjson::Document array by index

我有这个代码:

Document dataDoc;
dataDoc.SetArray();
Document::AllocatorType &allocator = dataDoc.GetAllocator();

for (size_t i = 0; i < 10; ++i)
{
    ostringstream ss;
    ss << "set_" << i + 1 << "_data";

    Document doc;
    doc.Parse<0>(UserDefault::getInstance()->getStringForKey(ss.str().c_str()).c_str());
    dataDoc.PushBack(doc, allocator);
}

有一个rapidjson::Document "dataDoc",我把它转换成一个数组。然后我用 Document 个对象填充数组,这些对象包含从 cocos2d::UserDefault 获取并适当解析的 JSON 个对象。

这是添加到 dataDoc 的 JSON 对象:

{
  "people": [
    {
      "name": "Peter",
      "phone": "123",
      "address": "Address 456"
    },
    {
      "name": "Helen",
      "phone": "123",
      "address": "Address 456"
    },
    {
      "name": "John",
      "phone": "123",
      "address": "Address 456"
    }
  ]
}

现在 dataDoc 数组包含 10 个这样的对象。

我知道我可以像这样处理一个对象:

Document doc;
rapidjson::Value &people = doc["people"];
string name = people[0]["name"].GetString();

但是我怎样才能通过索引访问 dataDoc 数组中的第一个对象并获得上面的名称值?

编辑

也尝试使用此代码:

vector<string> jsons;
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");
jsons.push_back("{\"people\":[{\"name\":\"Peter\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"Helen\",\"phone\":\"123\",\"address\":\"Address 456\"},{\"name\":\"John\",\"phone\":\"123\",\"address\":\"Address 456\"}]}");

Document dataDoc;
dataDoc.SetArray();
Document::AllocatorType &allocator = dataDoc.GetAllocator();

for (size_t i = 0; i < 3; ++i)
{
    Document doc;
    doc.Parse<0>(jsons.at(i).c_str());
    dataDoc.PushBack(doc, allocator);
}

auto &people = dataDoc[0]["people"];

但它给了我同样的错误。它指向位于 ...\cocos2d\external\json\.

的 "document.h" 中的第 1688 行

首先,您的代码创建方式似乎存在问题 doc - 您需要提供 dataDoc:

的分配器
Document doc(&allocator);

那么,rapidjson::Document继承自rapidjson::Value,所以你可以简单的把它当作一个值,使用[]运算符:

auto &people = dataDoc[0]["people"];

您还可以遍历整个文档:

for (auto &doc: dataDoc.getArray()) {
    auto &people = doc["people"];
}

C++11 之前的版本:

for (Value::ConstValueIterator itr = dataDoc.Begin(); 
     itr != dataDoc.End(); ++itr) {
    auto &people = (*itr)["people"];
}