ball.json 数据如下:
- {
- "entities":[
- {
- "entity":{
- "TapOpposite":0,
- "Interval":0.95,
- "BallNum":1
- }
- },248)"> {
- "entity":{
- "TapOpposite":0,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "Interval":0.91,248)"> "BallNum":2
- }
- },108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "BallNum":3
- ]
- }
在cocos2dx中json的读取是用的rapidjson,包含在cocostudio工程中。所以我们要先引入#include "cocostudio/CocoStudio.h"
- voidGameWorld::readJson()
- //json文档
- rapidjson::Document_doc;
- boolbRet=false;
- ssize_tsize=0;
- unsignedchar*pBytes=NULL;
- do{
- pBytes=cocos2d::CCFileUtils::sharedFileUtils()->getFileData("ball.json","r",&size);
- CC_BREAK_IF(pBytes==NULL||strcmp((char*)pBytes,"")==0);
- std::stringload_str((const 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"))
- //通过[]取成员值,再根据需要转为array,int,double,string
- constrapidjson::Value&pArray=_doc["entities"];
- //是否是数组
- if(!pArray.IsArray())
- return;
- for(rapidjson::SizeTypei=0;i<pArray.Size();i++)
- constrapidjson::Value&p=pArray[i];
- if(p.HasMember("entity"))
- constrapidjson::Value&valueEnt=p["entity"];
- if(valueEnt.HasMember("TapOpposite")&&valueEnt.HasMember("Interval")&&valueEnt.HasMember("BallNum"))
- constrapidjson::Value&tapOpposite=valueEnt["TapOpposite"];
- inttapOp=tapOpposite.GetInt();//得到int值
- constrapidjson::Value&interval=valueEnt["Interval"];
- floatinter=interval.GetDouble();//得到float,double值
- constrapidjson::Value&ballNum=valueEnt["BallNum"];
- intball=ballNum.GetInt(); ballParamparam;
- param.tapOp=tapOp;
- param.inter=inter;
- param.ballIndex=ball;
- m_ballParamVec.push_back(param);
- else
- bRet=true;
- }while(0);
- }