zoukankan      html  css  js  c++  java
  • cocos2dx 读取json及解析

    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,string
    		const 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);
    }



  • 相关阅读:
    安卓笔记:Android 界面设计指南——人人都是产品经理就是个玩笑话
    Windows CMD 命令
    安卓开发:dex 文件反编译
    VBA 学习笔记 运算符
    工商管理同等学力申硕全国统一考试资料整理
    VBA 学习笔记 判断语句、循环
    VBA 学习笔记 日期时间函数
    安卓自动领水果福气
    【合集】人大商学院同等学力工商管理
    安卓笔记:进度设计原则和常见错误
  • 原文地址:https://www.cnblogs.com/blfshiye/p/3789607.html
Copyright © 2011-2022 走看看