cocos2d读取json的方法(c++&lua)

    xiaoxiao2021-03-25  61

    1、json表如下: { "entities": [ { "entity": { "TapOpposite": 0, "Interval": 0.95, "BallNum": 1 } }, { "entity": { "TapOpposite": 0, "Interval": 0.91, "BallNum": 2 } }, { "entity": { "TapOpposite": 0, "Interval": 0.95, "BallNum": 3 } } ] } 读取函数如下:我们用到的是cocostudio中 rapidjson,包含在cocostudio工程中。所以我们要先引入#include "cocostudio/CocoStudio.h" void GameWorld::readJson() { //json 文档 rapidjson::Document _doc; bool bRet = false; ssize_t size = 0; unsigned char *pBytes = NULL; do { pBytes = cocos2d::CCFileUtils::sharedFileUtils()->getFileData("ball.json", "r", &size); CC_BREAK_IF(pBytes == NULL || strcmp((char*)pBytes, "") == 0); std::string load_str((const char*)pBytes, size); CC_SAFE_DELETE_ARRAY(pBytes); _doc.Parse<0>(load_str.c_str()); CC_BREAK_IF(_doc.HasParseError()); //生成json文档对像 if(!_doc.IsObject()) return; //是否有此成员 if(!_doc.HasMember("entities")) return; // 通过[]取成员值,再根据需要转为array,int,double,string const rapidjson::Value &pArray = _doc["entities"]; //是否是数组 if(!pArray.IsArray()) return; for (rapidjson::SizeType i = 0; i < pArray.Size(); i++) { const rapidjson::Value &p = pArray[i]; if(p.HasMember("entity")) { const rapidjson::Value &valueEnt = p["entity"]; if(valueEnt.HasMember("TapOpposite") && valueEnt.HasMember("Interval") && valueEnt.HasMember("BallNum")) { const rapidjson::Value &tapOpposite = valueEnt["TapOpposite"]; int tapOp = tapOpposite.GetInt(); //得到int值 const rapidjson::Value &interval = valueEnt["Interval"]; float inter = interval.GetDouble(); //得到float,double值 const rapidjson::Value &ballNum = valueEnt["BallNum"]; int ball = ballNum.GetInt(); //得到int值 } } else { return; } } bRet = true; } while (0); } 2、json表如下: [{"name":"zhangsan","age":20,"male":true},{"name":"lisi","age":30,"male":false}] #include <json/rapidjson.h> #include <json/document.h> void MyTest::readJson() { std::string strContent = FileUtils::getInstance()->getStringFromFile("data.json"); rapidjson::Document oDoc; oDoc.Parse<0>(strContent.c_str()); if (oDoc.HasParseError()) { log("Parse Error: %s\n", oDoc.GetParseError()); return false; } if (oDoc.IsNull() || !oDoc.IsArray()) { return false; } for (int i = 0; i < oDoc.Size(); i++) { if (oDoc[i]["name"].IsNull()) { return false; } log("name=========%s", oDoc[i]["name"].GetString()); if (oDoc[i]["age"].IsNull()) { return false; } log("name=========%d", oDoc[i]["age"].GetInt()); if (oDoc[i]["male"].IsNull()) { return false; } log("male=========%d", oDoc[i]["male"].GetBool()); } }后续会将lua的读取方式也更新上来
    转载请注明原文地址: https://ju.6miu.com/read-36643.html

    最新回复(0)