【问题标题】:cocos2d-x JSON file parsingcocos2d-x JSON文件解析
【发布时间】:2014-01-27 19:37:45
【问题描述】:

我有一个 .json 文件,其中包含一个字典数组。你能告诉我一个解析它的好方法吗?我用的是cocos2d-x 3.0-alpha版本和json类,放在external/json目录下。

我试过了:

Array* items = Array::createWithContentsOfFile("test.json");

string fullPath = CCFileUtils::getInstance()->fullPathForFilename("test.json");
long bufferSize = 0;
const char* mFileData = (const char*)FileUtils::getInstance()->getFileData(fullPath.c_str(), "r", &bufferSize);

string clearData(mFileData);
size_t pos = clearData.rfind("}");
clearData = clearData.substr(0, pos+1);

string data = clearData.c_str();

log("%s", clearData.c_str());

Json::Value _root;
Json::Reader reader;

reader.parse(data, _root);

但它们都不起作用——第一种方法返回一个空数组,第二种方法产生一个包含整个 json 的 _root 变量,但我不能将它变成一个数组并为每个数组创建一个单独的字典对象数组的元素(这是我想要做的)。

【问题讨论】:

  • 你可以使用rapidjson

标签: c++ json parsing cocos2d-x


【解决方案1】:

使用上面提到的 JsonCPP,但使用 CCFileUtils 类

unsigned long filesize = 0;
std::string content;
std::string fullPath = "path relative to your androidmanifest.xml/index.json"

unsigned char* fileData = CCFileUtils::sharedFileUtils()->getFileData(fullPath.c_str(), "r", &filesize);
content.append((char*)fileData);
delete[] fileData;

Json::Value jsonresult;
Json::Reader reader;
bool parsingSuccessful = reader.parse( content, jsonresult );
if ( !parsingSuccessful )
{
// report to the user the failure
return false;
}

【讨论】:

    猜你喜欢
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2018-10-10
    • 2019-06-09
    • 2020-04-12
    • 1970-01-01
    相关资源
    最近更新 更多