使用rapidjson从json文件获取数组数据 [英] get array data from json file using rapidjson
问题描述
我是Rapidjson的新手.我有test.json
其中包含{"points": [1,2,3,4]}
I'm new in rapidjson. I have test.json
which contains {"points": [1,2,3,4]}
并且我使用以下代码获取数组"points"
and I use following code to get data of array "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
)
as expected. But now when I try to get data (get x
and y
) from an array like this
{"points": [{"y": -14.25,"x": -2.25},{"y": -13.25,"x": -5.75},{"y": -12.5,"x": -7.25}]}
发生错误并在编译器中丢弃:
an error occured and threw away in compiler:
//! Get the number of elements in array.
SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
谁能解释我做错了什么或错过了什么?对不起,我的英语不好.
Can anyone explain what i did wrong or something's missed? Sorry for my bad English.
任何帮助将不胜感激.
谢谢.
推荐答案
最后我自己找到了,正确的语法是document["points"][0]["x"].GetString()
Finally found it myself, The correct syntax would be 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
Hope it helps. :D
这篇关于使用rapidjson从json文件获取数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!