Nik*_*eta 8 c++ rapidjson cocos2d-x-2.x
我是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());
Run Code Online (Sandbox Code Playgroud)
结果是
Cocos2d: a[0] = 1
Cocos2d: a[1] = 2
Cocos2d: a[2] = 3
Cocos2d: a[3] = 4
Run Code Online (Sandbox Code Playgroud)
正如所料.但是现在当我尝试从这样的数组中获取数据(get 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; }
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释我做错了什么或错过了什么?对不起,我的英语不好.
任何帮助将不胜感激.
谢谢.
使用索引枚举所有数组元素是正确的,但我个人觉得它已经过时了,因为引入了C++ 11 range-for.
使用C++ 11,您可以通过以下方式枚举值:
for(const auto& point : document["points"].GetArray()){
CCLOG("{x=%f, y=%f}", point["x"].GetDouble(), point["y"].GetDouble());
}
Run Code Online (Sandbox Code Playgroud)
您也可以以相同的方式枚举对象的字段(如果需要):
for(const auto& field : point.GetObject()) {
field.name.GetString(); // Use field's name somehow...
field.value.GetDouble(); // Use field's value somehow...
}
Run Code Online (Sandbox Code Playgroud)
终于自己找到了,正确的语法是 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());
}
Run Code Online (Sandbox Code Playgroud)
输出是
Cocos2d: {x=-2.250000, y=-14.250000}
Cocos2d: {x=-5.750000, y=-13.250000}
Cocos2d: {x=-7.250000, y=-12.500000}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。:D
| 归档时间: |
|
| 查看次数: |
12928 次 |
| 最近记录: |