Cocos2d-x Json读写

前端之家收集整理的这篇文章主要介绍了Cocos2d-x Json读写前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、Json读取
1. 读文件字符串

std::string data = FileUtils::getInstance()->getStringFromFile("test2.json");

2.解析字符串

Json::Reader reader;
Json::Value root;
reader.parse(data,root,false);

3.访问内容

log("id=%d",root["id"].asInt());
log("name=%s",root["name"].asCString());
log("IQ=%f",root["IQ"].asDouble());
log("msg value money=%d",root["msg"]["money"].asInt());
log("msg value say=%s",root["msg"]["say"].asCString());

示例:
test2.json:

{
“id”:1,
“name”:”mutou”,
“IQ”:99.5,
“msg”:{ “money”:999999,“say”:”hehe” }
}

代码

void HelloWorld::readChildJson()
{
    Json::Reader reader;
    Json::Value root;

    std::string data = FileUtils::getInstance()->getStringFromFile("test2.json");

    if (reader.parse(data,false) == true)
    {
        log("id=%d",root["id"].asInt());
        log("name=%s",root["name"].asCString());
        log("IQ=%f",root["IQ"].asDouble());

        log("msg value money=%d",root["msg"]["money"].asInt());
        log("msg value say=%s",root["msg"]["say"].asCString());
    }
}

二、Json写入
1.写内容

Json::Value root;
root["name"] = "Who";
root["IQ"] = 999;

2.生成Json字符串

Json::FastWriter writer;
std::string json_file = writer.write(root);

3.写入文件

FILE* file = fopen("testWirte.json","w");
fprintf(file,json_file.c_str());
fclose(file);

示例:

void HelloWorld::writeJson()
{

    Json::Value root;
    Json::FastWriter writer;

    root["name"] = "Who";
    root["IQ"] = 999;

    std::string json_file = writer.write(root);

    FILE* file = fopen("testWirte.json","w");
    fprintf(file,json_file.c_str());
    fclose(file);
}
原文链接:https://www.f2er.com/cocos2dx/339466.html

猜你在找的Cocos2d-x相关文章