Cocos2dx学习笔记37 Json 数据解析rapidjson库的使用

前端之家收集整理的这篇文章主要介绍了Cocos2dx学习笔记37 Json 数据解析rapidjson库的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原文地址:http://www.jb51.cc/article/p-rhfkjoll-sg.html

cocos2dx 2.2.x 版本以后,使用rapidjson进行数据解析,因为的效率要高写,下面是一个解析事例:

ball.json 数据如下:

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

在cocos2dx中json的读取是用的rapidjson,包含在libExtensions的CocoStudio的Json下:

所以在使用前我们需要引用命名空间和头文件

#include "cocos-ext.h"
USING_NS_CC_EXT;
using namespace rapidjson;


[cpp]
    voidGameWorld::readJson()
  1. @H_301_143@//json文档
  2. rapidjson::Document_doc;
  3. boolbRet=false;
  4. unsigned longsize=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();else
  33. bRet=true;
  34. }while(0);
  35. }
原文链接:https://www.f2er.com/cocos2dx/345959.html

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