您的位置:首页 > 移动开发 > Cocos引擎

【cocos2dx】rapidjson使用方法以及中文显示的解决方法

2014-02-18 22:28 726 查看
方法已更新,请移步新的地址:【cocos2dx】rapidjson使用方法以及中文显示的解决方法【续】

新版cocos2dx使用了rapidjson库来替换原来的jsoncpp。

解析速度提高了不少,但是好像没有那么方便。

今天想做一个读取中文数据的类。

磨磨蹭蹭也转了不少弯路,终于搞出来了一个可用的,数据使用JSON存储,下面是存储的数据

{"chinese":[{"ID":1,"String":"五子棋"},{"ID":2,"String":"当前玩家:"},{"ID":3,"String":"黑色方"},{"ID":4,"String":"白色方"},{"ID":5,"String":"选择玩家"},{"ID":6,"String":"失败"},{"ID":7,"String":"胜利"}]}


然后解析的类在这里,先是头文件ReadString.h

#pragma once
#include "cocos2d.h"
#include <string>
#include <cocos-ext.h>
#include "cocostudio\CocoStudio.h"
#include "gui\CocosGUI.h"

/**
* 数据ID的宏定义,用于找到中文数据
*/
#define S_GOBANG 1
#define S_NOWPLAY 2
#define S_BLACK 3
#define S_WHITE 4
#define S_CHOOSEPLAYER 5
#define S_FAIL 6
#define S_WIN 7

class ReadString
{
public:
static ReadString* creat(char * fileName);
static ReadString* getInstance();
~ReadString(void);
std::string read(int key);
private:
ReadString(char * fileName);
std::string Beffer; //暂存的数据
static ReadString* rs;
};


然后是实现文件ReadString.cpp

#include "ReadString.h"

using namespace std;
using namespace cocostudio;
ReadString* ReadString::rs = nullptr; //初始化
ReadString::ReadString(char * fileName)
{
auto File = cocos2d::FileUtils::getInstance();
string sFullPath = File->fullPathForFilename(fileName);
Beffer = File->getStringFromFile(sFullPath);
}
ReadString* ReadString::creat(char * fileName)
{
ReadString *RS = new ReadString(fileName);
return RS;
}

ReadString* ReadString::getInstance()
{
if(rs == nullptr)
rs= ReadString::creat("String.json");
return rs;
}

string ReadString::read(int key)
{
rapidjson::Document d;
d.Parse<0>(Beffer.c_str());
if (d.HasParseError())  //解析错误
{
CCLOG("GetParseError %s\n",d.GetParseError());
}
else if (d.IsObject()&&d.HasMember("chinese"))//这个时候要保证d.IsObject类型
{
const rapidjson::Value &a=d["chinese"];  //读取中文的数组
if (a.IsArray())  //判断是不是数组
{
for(unsigned int i=0;i<a.Size();++i) //如果不是数组,这一行会报错
{
const rapidjson::Value &val = a[i]; //得到单个对象
if(val.HasMember("ID")) //判断这个对象有没有id键
{
const rapidjson::Value &val_id = val["ID"]; //获取ID
int i_id = -1;
if(val_id.IsInt()) //判断ID类型
{
i_id = val_id.GetInt();
if(i_id == key) //如果ID与传入参数相同,则读取String键的内容
{
if(val.HasMember("String"))
if(val["String"].IsString())
return val["String"].GetString();
}
}
}
}
}
}
else return ""; //没查找到任何对象则返回空字符串
}

ReadString::~ReadString(void)
{
}


我比较喜欢把解释全写在代码里面

使用方法很简单

ReadString* rs = ReadString::getInstance(); //先获取静态类
std::string s_title = rs->read(S_GOBANG);//得到五子棋这个字符串


之后用来干什么都可以啦

这种方法的缺陷就是字符串添加比较麻烦,不过cocostudio的数据编辑器可以把excel的数据转换成json,方便一些。

唯一感觉比较麻烦的就是 宏定义需要自己维护
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2dx rapidjson
相关文章推荐