cocos2dx 读取json及解析

文章转载自:http://blog.csdn.net/cloud95/article/details/27643917

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,包含在cocostudio工程中。所以我们要先引入#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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值