Cocos2d-x的生成Json文件的方法(续)

本文承接自前文:http://blog.csdn.net/yuxikuo_1/article/details/39155335

1、JsonMake类

//.h
#include "cocos2d.h"
#include "../cocos2d/external/json/document.h"
#include "../cocos2d/external/json/writer.h"
#include "../cocos2d/external/json/stringbuffer.h"

USING_NS_CC;
using namespace rapidjson;

class JsonMake : public Ref
{
public:
    CREATE_FUNC(JsonMake);
    virtual bool init();
    std::string getJsonMyBaodanMain();
};

//.cpp
#include "JsonMake.h"
bool JsonMake::init()
{
    bool bRet = false;
    do{
        
        
        
        bRet = true;
    }while(0);
    return bRet;
}

std::string JsonMake::getJsonMyBaodanMain()
{    
    rapidjson::Document document;
    document.SetObject();
    
    rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
    rapidjson::Value object1(rapidjson::kObjectType);
    rapidjson::Value object2(rapidjson::kObjectType);
    rapidjson::Value object3(rapidjson::kObjectType);
    rapidjson::Value object4(rapidjson::kArrayType);
    
    object1.AddMember("Name","Yuxikuo",allocator);
    object1.AddMember("Age","18",allocator);
    object1.AddMember("Sex","man",allocator);
    
    object2.AddMember("Name","WangDongGe",allocator);
    object2.AddMember("Age","32",allocator);
    object2.AddMember("Sex","woman",allocator);

    object3.AddMember("Name","zhanhong",allocator);
    object3.AddMember("Age","20",allocator);
    object3.AddMember("Sex",allocator);

    object4.PushBack(object1,allocator);
    object4.PushBack(object2,allocator);
    object4.PushBack(object3,allocator);
    
    document.AddMember("info",object4,allocator);
    
    StringBuffer buffer;
    rapidjson::Writer<StringBuffer> writer(buffer);
    document.Accept(writer);
    log("%s",buffer.GetString());
    
    return StringUtils::format("%s",buffer.GetString());

}

2、使用方法

生成的json文件保存的本地
        auto path = FileUtils::getInstance()->getWritablePath();
        log("path = %s",path.c_str());
        path.append("myBaodanMain.json");
        FILE* fp = std::fopen(path.c_str(),"at+");
        CCASSERT(fp != NULL,"file open error");
        
        auto jsonMake = JsonMake::create();
        auto str = jsonMake->getJsonMyBaodanMain();
        auto length = str.length();
        fwrite(str.c_str(),length,1,fp);
        fclose(fp);

3、结果

//json
{"info":[{"Name":"Yuxikuo","Age":"18","Sex":"man"},{"Name":"WangDongGe","Age":"32","Sex":"woman"},{"Name":"zhanhong","Age":"20","Sex":"man"}]}

相关文章

操作步骤 1、创建cocos2d-x工程 2、新建 Scene1.cpp Scene1.h Scene1.h代码 #ifndef __SCENE1_H__#defi...
开发环境:OS(WINDOWS 8.1 X64 企业版) cocos2d-x 2.2.1 vs2010 想给vs安装上cocos的模版,执行Install...
把创建项目做成一个批处理,当创建项目时可以省时省力很多。 操作步骤 1、在 E:cocos2d-x-2.2.1toolspr...
https://www.cnblogs.com/JiaoQing/p/3906780.html 四个响应函数 1 EventListenerPhysicsContact* evC...
转载于 http://www.cnblogs.com/kenkofox/p/3926797.html 熟悉js的dom事件或者flash事件的,基本都能立...
ScrollView(滚动容器)加载大量item时会导致游戏界面的卡顿,严重时整个界面会出现卡死的情况。最近项...