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

前端之家收集整理的这篇文章主要介绍了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 "..\..\..\extensions\CocoStudio\Json\rapidjson\rapidjson.h"
#include "..\..\..\extensions\CocoStudio\Json\rapidjson\document.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} ]

原文链接:https://www.f2er.com/cocos2dx/342539.html

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