zoukankan      html  css  js  c++  java
  • Rapidjson的简单使用示例



    很早就想用用Markdown了,一直没机会。今天就来试一下

    先放个目录:


    rapidjson官方教程

    如果要想深入学习rapidjson工具,官方文档肯定是必须看一看的。官方教程里面的讲解才是最详细,最权威的了。


    本示例所用环境

    • 引擎版本:cocos2d-x 3.10

    示例代码与注释

    说明:我是直接使用原版引擎创建了新的cocos2dx工程,然后略微修改了HelloWorldScene.cpp中的代码。为了方便,使用rapidjson生成json串、保存json串到文件、从文件读取json串、使用rapidjson解析json串的过程,全部写到了initSelf()函数中。

    本身很反感blog全篇粘代码的方式(关键贴的代码谁都看不懂,一行注释没有),但是这部分代码示例没有什么可说的,所以在重点部分写了注释。

    HelloWorldScene.h文件内容

    #include "cocos2d.h"
    class HelloWorld : public cocos2d::Layer
    {
    public:
        static cocos2d::Scene* createScene();
        virtual bool init();
        CREATE_FUNC(HelloWorld);
    private:
        void initSelf();
    };

    HelloWorldScene.cpp文件内容

    #include "HelloWorldScene.h"
    
    #include "json/rapidjson.h"
    #include "json/document.h"
    #include "json/filestream.h"
    #include "json/stringbuffer.h"
    #include "json/writer.h"
    
    USING_NS_CC;
    
    Scene* HelloWorld::createScene()
    {
        auto scene = Scene::create();
        auto layer = HelloWorld::create();
        scene->addChild(layer);
        return scene;
    }
    
    bool HelloWorld::init()
    {
        if ( !Layer::init() )
        {
            return false;
        }
        else {
            this->initSelf();
            return true;
        }
    }
    
    //重点
    void HelloWorld::initSelf()
    {
    //生成一串如下的json格式字符串,并解析
    // {
    // "name":"qfl",
    // "age":20,
    // "letter":["a","b","c"],
    // "location": {"province":"fujian","city":"xiamen","number":16}
    // "book":[{"name":"book1", "isbn":"123"},{"name":"book2","isbn":"456"}],
    // "healthy":true,
    // }
    
        //生成Json串
        rapidjson::Document jsonDoc;    //生成一个dom元素Document
        rapidjson::Document::AllocatorType &allocator = jsonDoc.GetAllocator(); //获取分配器
        jsonDoc.SetObject();    //将当前的Document设置为一个object,也就是说,整个Document是一个Object类型的dom元素
    
        //添加属性
        jsonDoc.AddMember("name", "qfl", allocator);    //添加字符串值
        jsonDoc.AddMember("age", 20, allocator);        //添加int类型值
    
        //生成array
        rapidjson::Value letterArray(rapidjson::kArrayType);//创建一个Array类型的元素
        letterArray.PushBack("a", allocator);
        letterArray.PushBack("b", allocator);
        letterArray.PushBack("c", allocator);
        jsonDoc.AddMember("letter", letterArray, allocator);    //添加数组
    
        //生成一个object
        rapidjson::Value locationObj(rapidjson::kObjectType);//创建一个Object类型的元素
        locationObj.AddMember("province", "fujian", allocator);
        locationObj.AddMember("city", "xiamen", allocator);
        locationObj.AddMember("number", 16, allocator);
        jsonDoc.AddMember("location", locationObj, allocator);  //添加object到Document中
    
        //生成一个object数组
        rapidjson::Value bookArray(rapidjson::kArrayType);//生成一个Array类型的元素,用来存放Object
        rapidjson::Value book1(rapidjson::kObjectType); //生成book1
        book1.AddMember("name", "book1", allocator);
        book1.AddMember("isbn", "123", allocator);
        bookArray.PushBack(book1, allocator);           //添加到数组
    
        rapidjson::Value book2(rapidjson::kObjectType); //生成book2
        book2.AddMember("name", "book2", allocator);
        book2.AddMember("isbn", "456", allocator);
        bookArray.PushBack(book2, allocator);           //添加到数组
        jsonDoc.AddMember("book", bookArray, allocator);
    
        //添加属性
        jsonDoc.AddMember("healthy", true, allocator);  //添加bool类型值
    // jsonDoc.AddMember("sports", NULL, allocator);//添加空值,这里会导致报错
    
        //生成字符串
        rapidjson::StringBuffer buffer;
        rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
        jsonDoc.Accept(writer);
    
        std::string strJson = buffer.GetString();
        log("-----生成的Json:
    %s", strJson.c_str());
    
        //写到文件
        std::string strPath = FileUtils::getInstance()->getWritablePath() + "JsonFile.txt";
        FILE* myFile = fopen(strPath.c_str(), "w");  //windows平台要使用wb
        if (myFile) {
            fputs(buffer.GetString(), myFile);
            fclose(myFile);
        }
    
        //JsonFile.txt文件内容
        //{"name":"qfl","age":20,"letter":["a","b","c"],"location":{"province":"fujian","city":"xiamen","number":16},"book":[{"name":"book1","isbn":"123"},{"name":"book2","isbn":"456"}],"healthy":true}
    
        log("-----读取Json内容:");
        //从文件中读取(注意和上面分开,不能确定文件是否生成完毕,这里读取可能有问题)
        rapidjson::Document newDoc;
        myFile = fopen(strPath.c_str(), "r");   //windows平台使用rb
        if (myFile) {
            rapidjson::FileStream inputStream(myFile);  //创建一个输入流
            newDoc.ParseStream<0>(inputStream); //将读取的内容转换为dom元素
            fclose(myFile); //关闭文件,很重要
        }
        //判断解析从流中读取的字符串是否有错误
        if (newDoc.HasParseError()) {
            log("Json Parse error:%d", newDoc.GetParseError()); //打印错误编号
        }
        else {
            //获取json串中的数据
            //先判断是否有这个字段,如果使用不存在的key去取值会导致直接崩溃
            if (newDoc.HasMember("name")) {
                log("name:%s", newDoc["name"].GetString()); //必须要获取对应的数据类型,rapidjson不会帮你转换类型
            }
            else {}
    
            if (newDoc.HasMember("age")) {
                log("age:%d", newDoc["age"].GetInt());  //获取正确的类型
            }
            else {}
    
            if (newDoc.HasMember("letter")) {
                rapidjson::Value letter;    //使用一个新的rapidjson::Value来存放array的内容
                letter = newDoc["letter"];
    
                //确保它是一个Array,而且有内容
                if (letter.IsArray() && !letter.Empty()) {
                    //遍历Array中的内容
                    for (rapidjson::SizeType i = 0; i < letter.Size(); i++) {
                        log("letter:%s", letter[i].GetString());
                    }
                }
                else {}
            }
            else {}
    
            if (newDoc.HasMember("location")) {
                rapidjson::Value location;      //使用一个新的rapidjson::Value来存放object
                location = newDoc["location"];
    
                //确保它是一个Object
                if (location.IsObject()) {
    
                    if (location.HasMember("province")) {
                        log("location:province:%s", location["province"].GetString());
                    }
                    else {}
                    if (location.HasMember("city")) {
                        log("location:city:%s", location["city"].GetString());
                    }
                    else {}
                    if (location.HasMember("number")) {
                        log("location:number:%d", location["number"].GetInt());
                    }
                    else {}
                }
                else {}
            }
            else {}
    
            //book是一个包含了2个object的array。按照上面的步骤来取值就行
            if (newDoc.HasMember("book")) {
                rapidjson::Value book;
                book = newDoc["book"];
    
                //先取Array
                if (book.IsArray() && !book.Empty()) {
    
                    rapidjson::Value tempBook;
                    for (rapidjson::SizeType i = 0; i < book.Size(); i++) {
                        tempBook = book[i]; //Array中每个元素又是一个Object
    
                        if (tempBook.IsObject()) {
    
                            if (tempBook.HasMember("name") && tempBook.HasMember("isbn")) {
                                log("book:%d:name:%s, isbn:%s", i, tempBook["name"].GetString(), tempBook["isbn"].GetString());
                            }
                            else {}
                        }
                        else {}
                    }
                }
                else {}
            }
            else {}
    
            if (newDoc.HasMember("healthy")) {
                if (newDoc["healthy"].GetBool()) {
                    log("healthy:true");
                }
                else {
                    log("healthy:false");
                }
            }
            else {}
        }
    }
  • 相关阅读:
    8.10
    今日头条笔试题 1~n的每个数,按字典序排完序后,第m个数是什么?
    Gym 100500B Conference Room(最小表示法,哈希)
    CodeForces 438D The Child and Sequence(线段树)
    UVALIVE 6905 Two Yachts(最小费用最大流)
    Gym Conference Room (最小表示法,哈希)
    hdu 2389 Rain on your Parade(二分图HK算法)
    Codeforces Fox And Dinner(最大流)
    zoj 3367 Counterfeit Money(dp)
    ZOJ3370. Radio Waves(2-sat)
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9410032.html
Copyright © 2011-2022 走看看