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();

    @H_502_32@// 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);

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

#endif // __TestRapidJson_SCENE_H__

TestRapidJson.cppc文件

#include "TestRapidJson.h"
@H_502_32@//#include "cocos2d\external\json\rapidjson.h"
@H_502_32@//#include "cocos2d\external\json\document.h"
@H_502_32@//#include "cocos2d\external\json\stringbuffer.h"
@H_502_32@//#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()
{
    @H_502_32@// 'scene' is an autorelease object
    auto scene = Scene::create();

    @H_502_32@// 'layer' is an autorelease object
    auto layer = TestRapidJson::create();

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

    @H_502_32@// return the scene
    return scene;
}

@H_502_32@// on "init" you need to initialize your instance
bool TestRapidJson::init()
{
    @H_502_32@//////////////////////////////
    @H_502_32@// 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    @H_502_32@//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())
    {
        @H_502_32@/*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());

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

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

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

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


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

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

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

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

            @H_502_32@//添加一个数组
            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);







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

        }
        @H_502_32@//=============解析Json==================




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





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

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