9

我是 rapidjson 的新手。我有test.json其中包含{"points": [1,2,3,4]}

我使用以下代码获取数组数据"points"

std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("json/deluxe/treasurebag.json");

    unsigned long bufferSize = 0;

    const char* mFileData = (const char*)CCFileUtils::sharedFileUtils()->getFileData(fullPath.c_str(), "r", &bufferSize);

    std::string clearData(mFileData);
    size_t pos = clearData.rfind("}");
    clearData = clearData.substr(0, pos+1);
    document.Parse<0>(clearData.c_str());
    assert(document.HasMember("points"));

    const Value& a = document["points"]; // Using a reference for consecutive access is handy and faster.
    assert(a.IsArray());
    for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
        CCLOG("a[%d] = %d\n", i, a[i].GetInt());

结果是

Cocos2d: a[0] = 1
Cocos2d: a[1] = 2
Cocos2d: a[2] = 3
Cocos2d: a[3] = 4

正如预期的那样。但是现在当我尝试从这样的数组中获取数据(获取x和)时y

{"points": [{"y": -14.25,"x": -2.25},{"y": -13.25,"x": -5.75},{"y": -12.5,"x": -7.25}]}

发生错误并在编译器中丢弃:

//! Get the number of elements in array.
    SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }

谁能解释我做错了什么或遗漏了什么?对不起,我的英语不好。

任何帮助将不胜感激。

谢谢。

4

2 回答 2

10

使用索引来枚举所有数组元素是正确的,但我个人认为它已经过时了,因为引入了 C++11 range-for。

使用 C++11,您可以通过以下方式枚举值:

for(const auto& point : document["points"].GetArray()){
    CCLOG("{x=%f, y=%f}", point["x"].GetDouble(), point["y"].GetDouble());
}

您还可以以相同的方式枚举对象的字段(如果需要):

for(const auto& field : point.GetObject()) {
    field.name.GetString(); // Use field's name somehow...
    field.value.GetDouble(); // Use field's value somehow...
}
于 2017-08-17T07:26:39.807 回答
6

终于自己找到了,正确的语法是document["points"][0]["x"].GetString()

for (SizeType i = 0; i < document["points"].Size(); i++){
    CCLOG("{x=%f, y=%f}", document["points"][i]["x"].GetDouble(), document["points"][i]["y"].GetDouble());
}

输出是

Cocos2d: {x=-2.250000, y=-14.250000}
Cocos2d: {x=-5.750000, y=-13.250000}
Cocos2d: {x=-7.250000, y=-12.500000}

希望能帮助到你。:D

于 2014-11-11T08:32:22.873 回答