加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2d-x解析Json(使用rapidjson)

发布时间:2020-12-14 18:54:29 所属栏目:百科 来源:网络整理
导读:TestRapidJson.h文件: #ifndef __TestRapidJson_SCENE_H__ # define __TestRapidJson_SCENE_H__ #include "cocos2d.h" #include "networkHttpRequest.h" #include "networkHttpClient.h" #include "networkHttpResponse.h" USING_NS_CC; using namespace

TestRapidJson.h文件:

#ifndef __TestRapidJson_SCENE_H__
#define __TestRapidJson_SCENE_H__

#include "cocos2d.h"

#include "networkHttpRequest.h"
#include "networkHttpClient.h"
#include "networkHttpResponse.h"

USING_NS_CC;
using namespace cocos2d::network;

class TestRapidJson : public cocos2d::Layer
{
public:
    // there's no 'id' in cpp,so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
    virtual bool init();

    void complete(HttpClient *client,HttpResponse *response);

    // implement the "static create()" method manually
    CREATE_FUNC(TestRapidJson);
};

#endif // __TestRapidJson_SCENE_H__

TestRapidJson.cppc文件:

#include "TestRapidJson.h"
//#include "cocos2dexternaljsonrapidjson.h"
//#include "cocos2dexternaljsondocument.h"
//#include "cocos2dexternaljsonstringbuffer.h"
//#include "cocos2dexternaljsonwriter.h"
#include "jsonrapidjson.h"
#include "jsondocument.h"
#include "jsonstringbuffer.h"
#include "jsonwriter.h"


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

    // 'layer' is an autorelease object
    auto layer = TestRapidJson::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 TestRapidJson::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    //post 
    auto postReq = new HttpRequest();
    postReq->setTag("type post");
    postReq->setUrl("http://httpbin.org/post");
    postReq->setRequestType(HttpRequest::Type::POST);
    std::vector<std::string> header;
    header.push_back("Content-Type:application/json;charset=utf-8");
    postReq->setHeaders(header);
    const char* reqData = "response Data";
    postReq->setRequestData(reqData,strlen(reqData));
    postReq->setResponseCallback(CC_CALLBACK_2(TestRapidJson::complete,this));

    auto client2 = HttpClient::getInstance();
    client2->send(postReq);
    postReq->release();

    return true;
}
void TestRapidJson::complete(HttpClient *client,HttpResponse *response)
{
    log("request tag is:%s",response->getHttpRequest()->getTag());
    log("response code is:%d",response->getResponseCode());
    if(response->isSucceed())
    {
        /*std::vector<char> * data = response->getResponseData(); log("response data is:"); for (int i = 0; i < data->size(); i++) { log("%c",(*data)[i]); }*/
        std::vector<char> * data = response->getResponseData();
        std::stringstream oss;
        for (int i = 0; i < data->size(); i++)
        {
            oss<<(*data)[i];
        }
        std::string str = oss.str();
        log("response data is:%s",str.c_str());

//=============解析Json(增删改查)==================
        rapidjson::Document doc;
        doc.Parse<0>(str.c_str());
        if (doc.HasParseError())
        {
            log("json parse error : %s",doc.GetParseError());
        }else//解析成功之后的操作
        {
            log("parse success");
            /* HasMember方法:判断是否有这个键值对 IsObject方法:判断是否是对象 IsString方法:判断是否是字符串 IsArray方法:判断是否是数组 */

            if (doc.IsObject()&&doc.HasMember("data"))
            {
                //取值
                rapidjson::Value &value = doc["data"];
                if (value.IsString())
                {
                    log("data is :%s",value.GetString());
                }
            }

            if (doc.IsObject()&&doc.HasMember("json"))
            {
                //设值
                doc["json"].SetInt(15);
                log("json is :% d",doc["json"].GetInt() );
            }

            //声明一个类型的数据(#include "jsonstringbuffer.h")
            rapidjson::StringBuffer buffer;
            //创建一个rapidjson::Writer对象
            rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
            doc.Accept(writer);
            //这样就可以获取字符串了
            log("json string is: %s",buffer.GetString());


            rapidjson::Document::AllocatorType &allocator=doc.GetAllocator();
            //添加整数
            doc.AddMember("int",20,allocator);

            //添加字符串
            doc.AddMember("string","string value",allocator);

            //添加一个null对象
            rapidjson::Value nullObj(rapidjson::kNullType);
            doc.AddMember("null",nullObj,allocator);

            //添加了一个对象
            rapidjson::Value obj(rapidjson::kObjectType);
            obj.AddMember("name","xiaoli",allocator);
            obj.AddMember("age",allocator);
            obj.AddMember("height",180,allocator);
            doc.AddMember("personInfo",obj,allocator);

            //添加一个数组
            rapidjson::Value arr(rapidjson::kArrayType);
            arr.PushBack(1,allocator);
            arr.PushBack("string in array",allocator);
            rapidjson::Value obj1(rapidjson::kObjectType);
            obj1.AddMember("name",allocator);
            obj1.AddMember("age",allocator);
            obj1.AddMember("height",allocator);
            arr.PushBack(obj1,allocator);       
            doc.AddMember("arr",arr,allocator);







            //添加完之后,重新打印输出本Json
            rapidjson::StringBuffer buffer1;
            rapidjson::Writer<rapidjson::StringBuffer> writer1(buffer1);
            doc.Accept(writer1);
            log("modified data is: %s",buffer1.GetString());

        }
        //=============解析Json==================




    }else
    {
        log("error msg is:%s",response->getErrorBuffer());
    }
}





///*
//request tag is:type post
//response code is:200
//response data is:{
//"args": {},
//"data": "response Data",
//"files": {},
//"form": {},
//"headers": {
//"Accept": "*/*",
//"Accept-Encoding": "deflate,gzip",
//"Content-Length" : "13",
//"Content-Type" : "application/json;charset=utf-8",
//"Host" : "httpbin.org"
// },
// "json": null,
// "origin" : "171.39.213.117",
// "url" : "http://httpbin.org/post"
//}
//
//*/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读