#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
using namespace CSJson;
从cocos2dx 2.2版本后 就不需要开发者手动添加jsoncpp第三方库 在自己封装解析json相关功能的时候 只需要在类中添加这样的头文件 就可以正常使用相关变量和方法了
Value 对象可以指向任何类型 有点像c++中的 void* 类型
Reader 对象解析json 得到value对象
FastWriter对象 将Value数据按照编码格式生成json格式
Value array;
解析一个json文件函数
/读取一个jeson文件 并将其转换为Value
Value CCAnalysisJeson::ReadJson(const char * filename)
{
unsigned long size;
const char* file=(char*)CCFileUtils::sharedFileUtils()->getFileData(filename,"r",&size);
CCLOG("%s",file);
Reader reader;
if(!reader.parse(std::string(file),array,false))
{
return 0;
}
return array;
}
//根据一个Key值获得对应的Value
Value CCAnalysisJeson::GetValue(Value root, const char *keyname)
{
Value val;
val=root.get(keyname,val);
return val;
}
完成以上两个函数 则可以根据json文件的键值的名字获取对应的值
比如从json中获取玩家的姓名
string CCAnalysisJeson::GetPalyerName(const char* filename,int index)
{
ReadJson(filename);
string strPlayName=GetValue(array[index],"name").asString();
return strPlayName;
}