按索引

时间:2017-07-05 13:36:16

标签: c++ arrays cocos2d-x rapidjson

我有这段代码:

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行。

1 个答案:

答案 0 :(得分:0)

首先,您的代码中创建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"];
}