cocos2dx 讀取json及解析

來源:互聯網
上載者:User

標籤:class   blog   code   get   資料   2014   

ball.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            }        }    ]}

在cocos2dx中json的讀取是用的rapidjson,包括在cocostudioproject中。所以我們要先引入#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,stringconst 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值ballParam param;param.tapOp = tapOp;param.inter = inter;param.ballIndex = ball;m_ballParamVec.push_back(param);}}else{return;}}bRet = true;} while (0);}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.