cocos2d-x解析Json(使用rapidjson)

前端之家收集整理的这篇文章主要介绍了cocos2d-x解析Json(使用rapidjson)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

TestRapidJson.h文件

#ifndef __TestRapidJson_SCENE_H__
#define __TestRapidJson_SCENE_H__

#include "cocos2d.h"

#include "network\HttpRequest.h"
#include "network\HttpClient.h"
#include "network\HttpResponse.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 "cocos2d\external\json\rapidjson.h"
//#include "cocos2d\external\json\document.h"
//#include "cocos2d\external\json\stringbuffer.h"
//#include "cocos2d\external\json\writer.h"
#include "json\rapidjson.h"
#include "json\document.h"
#include "json\stringbuffer.h"
#include "json\writer.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 "json\stringbuffer.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"
//}
//
//*/
原文链接:https://www.f2er.com/cocos2dx/340488.html

猜你在找的Cocos2d-x相关文章