加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 19:33:50 所属栏目:百科 来源:网络整理
导读:原文地址:http://www.jb51.cc/article/p-rhfkjoll-sg.html cocos2dx 2.2.x 版本以后,使用 rapidjson进行数据解析,因为的效率要高写,下面是一个解析事例: ball.json 数据如下: [html] view plain copy { "entities":[ { "entity":{ "TapOpposite":0, "I

原文地址:http://www.52php.cn/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. //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. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读