Rapidjsonの簡単な使用(json列をつなぎ合わせて、ファイルの中のjsonにアクセスして、json列を解析します)


日文教程:クリックしてリンクを開く
ディレクトリを先に置く:
Rapidjsonの簡単な使用例
rapidjson公式チュートリアルこの例で使用する環境サンプルコードとコメント
rapidjson公式チュートリアル
rapidjsonツールを深く学ぶには、公式ドキュメントを見なければならないに違いありません.公式チュートリアルの中の説明こそ最も詳細で、最も権威がある.
この例で使用する環境
エンジンバージョン:cocos 2 d-x 3.10サンプルコードとコメント
説明:私はオリジナルエンジンを直接使って新しいcocos 2 dxプロジェクトを作成し、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<: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 {} } }