18.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",20,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","xiaoli",allocator);
            obj1.AddMember("age",20,allocator);
            obj1.AddMember("height",180,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"
//}
//
//*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值