Cocos2d-x3.1生成Json串

#include "HelloWorldScene.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    bool bRet = false;
    do{
        CC_BREAK_IF(!Layer::init());

        auto path = FileUtils::getInstance()->getWritablePath();
        log("path = %s",path.c_str());
        path.append("test.json");
        
        rapidjson::Document document;
        document.SetObject();

        rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
        rapidjson::Value array(rapidjson::kArrayType);
        rapidjson::Value array1(rapidjson::kArrayType);
        rapidjson::Value object(rapidjson::kObjectType);
        rapidjson::Value object1(rapidjson::kObjectType);

        object.AddMember("TransType","CALLCENTER", allocator);
        object.AddMember("TransCode",00011002, allocator);
        object.AddMember("SubTransCode",2, allocator);
        object.AddMember("TransDate",2013-6-17, allocator);
        object.AddMember("TransTime","15:23:25", allocator);
        object.AddMember("TransSeq",00011002-2201361700017, allocator);
        object.AddMember("Operator","web", allocator);
        object.AddMember("RowNumStart",1, allocator);
        object.AddMember("PageRowNum",1000, allocator);
        object.AddMember("PageFlag",0, allocator);
        object.AddMember("TotalRowNum","", allocator);
        object.AddMember("ResultCode","", allocator);
        object.AddMember("ResultMsg","", allocator);
        object.AddMember("OrderFlag",0, allocator);
        object.AddMember("OrderField","", allocator);
        array.PushBack(object, allocator);
        
        object1.AddMember("ContNo",662206117012, allocator);
        array1.PushBack(object1, allocator);
        
        document.AddMember("BaseInfo",array, allocator);
        document.AddMember("InputData",array1, allocator);
        
        
        StringBuffer buffer;
        rapidjson::Writer<StringBuffer> writer(buffer);
        document.Accept(writer);
        log("%s",buffer.GetString());
        
        FILE* fp = std::fopen(path.c_str(), "at+");
        CCASSERT(fp != NULL, "file open error");
        auto str = StringUtils::format("%s",buffer.GetString());
        auto length = str.length();
        log("length = %lu",str.length());
        fwrite(str.c_str(), length, 1, fp);
        fclose(fp);

        
        bRet = true;
    }while(0);
    return bRet;
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。