Cocos2dx------从json文件读取数据

ReadJson.h文件代码

#ifndef __Read_Json_H__

#define __Read_Json_H__
#include "cocos2d.h"
#include <array>
USING_NS_CC;
using namespace std;


class LayoutInfo:public CCObject 
{
public:
int Num;
int Value;
};


class ReadJson{
public:
static CCArray* parseLayoutInfo(int num);
};

#endif



ReadJson.cpp文件代码

#include "ReadJson.h"
#include "......extensionsCocoStudioJsonrapidjsonrapidjson.h"
#include "......extensionsCocoStudioJsonrapidjsondocument.h"


CCArray* ReadJson::parseLayoutInfo(int num)
{
CCArray* settingArray=new CCArray();


char fileName[64];
sprintf(fileName,"Layout%d.json",num);

rapidjson::Document doc; 
//判断文件是否存在 
if(!CCFileUtils::sharedFileUtils()->isFileExist(fileName)) 

CCLOG("json file is not find [%s]",fileName);
return settingArray; 

//读取文件数据,初始化doc 
unsigned long bufferSize = 0; 
unsigned char* data=CCFileUtils::sharedFileUtils()->getFileData(fileName,"rb",&bufferSize); 
std::string load_str((const char*)data, bufferSize); 
doc.Parse<rapidjson::kParseDefaultFlags>(load_str.c_str()); 
//判断读取成功与否 和 是否为数组类型 
if (doc.HasParseError() || !doc.IsArray()) 

CCLOG("get json data err!"); 
return settingArray; 

for(unsigned int i=0;i<doc.Size();i++) 

//逐个提取数组元素(声明的变量必须为引用) 
rapidjson::Value &v=doc[i]; 



if(v.HasMember("Num") && v.HasMember("Value")) 

LayoutInfo* info=new LayoutInfo();

info->Num=v["Num"].GetInt(); 
info->Value=v["Value"].GetInt(); 

settingArray->addObject(info);


return settingArray;
}



Layout1.json文件的内容如下(该文件要ANSI编码格式)

[
{"Num":1,"Value":14},
{"Num":2,"Value":10},
{"Num":3,"Value":5},
{"Num":4,"Value":8},
{"Num":5,"Value":13},
{"Num":6,"Value":16},
{"Num":7,"Value":1},
{"Num":8,"Value":4},
{"Num":9,"Value":6},
{"Num":10,"Value":7}
]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值