cocos2dx 读取json及解析

ball.json 数据如下:

  1. {
  2. "entities":[
  3. {
  4. "entity":{
  5. "TapOpposite":0,
  6. "Interval":0.95,
  7. "BallNum":1
  8. }
  9. },248)"> {
  10. "entity":{
  11. "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
  12. }
  13. },108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "BallNum":3
  14. ]
  15. }



在cocos2dx中json的读取是用的rapidjson,包含在cocostudio工程中。所以我们要先引入#include "cocostudio/CocoStudio.h"


    voidGameWorld::readJson()
  1. //json文档
  2. rapidjson::Document_doc;
  3. boolbRet=false;
  4. ssize_tsize=0;
  5. unsignedchar*pBytes=NULL;
  6. do{
  7. pBytes=cocos2d::CCFileUtils::sharedFileUtils()->getFileData("ball.json","r",&size);
  8. CC_BREAK_IF(pBytes==NULL||strcmp((char*)pBytes,"")==0);
  9. std::stringload_str((const CC_SAFE_DELETE_ARRAY(pBytes);
  10. _doc.Parse<0>(load_str.c_str());
  11. CC_BREAK_IF(_doc.HasParseError());
  12. //生成json文档对像
  13. if(!_doc.IsObject())
  14. return;
  15. //是否有此成员
  16. if(!_doc.HasMember("entities"))
  17. //通过[]取成员值,再根据需要转为array,int,double,string
  18. constrapidjson::Value&pArray=_doc["entities"];
  19. //是否是数组
  20. if(!pArray.IsArray())
  21. return;
  22. for(rapidjson::SizeTypei=0;i<pArray.Size();i++)
  23. constrapidjson::Value&p=pArray[i];
  24. if(p.HasMember("entity"))
  25. constrapidjson::Value&valueEnt=p["entity"];
  26. if(valueEnt.HasMember("TapOpposite")&&valueEnt.HasMember("Interval")&&valueEnt.HasMember("BallNum"))
  27. constrapidjson::Value&tapOpposite=valueEnt["TapOpposite"];
  28. inttapOp=tapOpposite.GetInt();//得到int值
  29. constrapidjson::Value&interval=valueEnt["Interval"];
  30. floatinter=interval.GetDouble();//得到float,double值
  31. constrapidjson::Value&ballNum=valueEnt["BallNum"];
  32. intball=ballNum.GetInt(); ballParamparam;
  33. param.tapOp=tapOp;
  34. param.inter=inter;
  35. param.ballIndex=ball;
  36. m_ballParamVec.push_back(param);
  37. else
  38. bRet=true;
  39. }while(0);
  40. }

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...