RapidJSON の基本的な使い方
[履歴] [最終更新] (2020/01/28 00:19:17)
プログラミング/IoT の関連商品 (Amazonのアソシエイトとして、当メディアは適格販売により収入を得ています。)
最近の投稿
注目の記事

概要

C++ で JSON を扱う際に利用されるライブラリの一つに RapidJSON があります。基本的な使い方を記載します。

インストール

cmake を利用してビルドすると簡単です。

ヘッダーファイルのみが必要となります。

git clone https://github.com/Tencent/rapidjson.git
ls rapidjson/include/
rapidjson

CMakeLists.txt

cmake_minimum_required (VERSION 3.10)
add_executable(main main.cpp)
target_include_directories(main PRIVATE rapidjson/include)

main.cpp

各値は rapidjson::Value として扱われます。rapidjson::Document は DOM を表現しており、一つ以上の rapidjson::Value を持ちます。

#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <iostream>

int main() {

    // JSON 文字列をパースして DOM に変換します。
    std::string json = "{\"project\":\"rapidjson\",\"stars\":10}";
    rapidjson::Document d;
    d.Parse(json.c_str());

    // 内容を Get/Set します。
    rapidjson::Value& s = d["stars"];
    s.SetInt(s.GetInt() + 1);

    // buffer、writer を作成した上で、DOM と関連付けます。
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    d.Accept(writer);

    // buffer を経由して値を文字列として取り出せます。
    std::cout << buffer.GetString() << std::endl;

    return 0;
}

ビルドおよび実行例

mkdir build
cd build/
cmake ..
make
./main
{"project":"rapidjson","stars":11}

サンプルコード

#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <iostream>

int main() {

    // 検証用の JSON を用意します。
    std::string json = "{\"key\":\"aaa\", \"key2\":123, \"key3\":true, \"\key4\": null, \"\key5\":1.23}";
    rapidjson::Document d;
    d.Parse(json.c_str());

    std::string json2 = "[{\"key\":\"aaa\", \"key2\":123}]";
    rapidjson::Document d2;
    d2.Parse(json2.c_str());

    // root [] または {} です。
    assert(!d.IsArray());
    assert(d.IsObject());
    assert(d2.IsArray());
    assert(!d2.IsObject());

    // キーの存在確認
    assert(d.HasMember("key"));

    // 型の確認
    assert(d["key"].IsString());
    std::cout << d["key"].GetString() << std::endl; //=> aaa

    assert(d["key2"].IsInt());
    std::cout << d["key2"].GetInt() << std::endl; //=> 123

    assert(d["key5"].IsDouble());
    std::cout << d["key5"].GetDouble() << std::endl; //=> 1.23

    assert(d["key3"].IsBool());
    assert(d["key3"].GetBool());

    assert(d["key4"].IsNull());

    // JSON 配列
    for(rapidjson::SizeType i = 0; i < d2.Size(); i++) {
        assert(d2[i].IsObject());
        assert(d2[i]["key"].IsString());
    }

    // 型の判別
    static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
    for (rapidjson::Value::ConstMemberIterator itr = d.MemberBegin(); itr != d.MemberEnd(); ++itr) {
        printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]);
    }

    return 0;
}
関連ページ