无法处理 cocos2dx 中的 JSON 响应

Unable to handle JSON responce in cocos2dx

我想通过以下代码在我的游戏中使用网络服务:

std::vector<char> *dataa = response->getResponseData();
std::string ret(&(dataa->front()), dataa->size());
CCLOG("%s", ("Response message: " + ret).c_str());

ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(ret.c_str());

变量 dict 被赋值为 "nil"。是否可以在不创建文件的情况下获得非空ValueMap

您没有名为 ret 内容的文件,因此 FileUtils::getInstance()->getValueMapFromFile 无法帮助您。如果您正在使用 XML,您可以尝试 FileUtils::getInstance()->getValueMapFromData。 你真正需要的是一个 JSON 解析器,我喜欢使用 rapidjson
Cocos2dx 已经捆绑了 rapidjson。

#define RAPIDJSON_HAS_STDSTRING 1
#include "json/document.h"

using namespace rapidjsonl
Document doc;
doc.Parse(ret.c_str());

/* if ret is as follows
{
    "hello": "world",
    "t": true ,
    "f": false,
    "n": null,
    "i": 123,
    "pi": 3.1416,
    "a": [1, 2, 3, 4]
}
*/
assert(document.HasMember("hello"));
assert(document["hello"].IsString());
log("hello = %s\n", document["hello"].GetString());