俺、サービス売って家買うんだ

Swift, Kotlin, Vue.js, 統計, GCP / このペースで作ってればいつか2-3億で売れるのがポっと出来るんじゃなかろうか

【Cocos2d-x】RapidJSONの使い方メモ

f:id:ie-kau:20150918142357p:plain


最近Cocos2d-xで開発しているのですが、JSONを使いたい時が結構あります。

  • 構造化したデータをUserDefaultに保存したいけど、SQLiteを入れるほどではない
  • APIをJSONで作成してネットワーク通信させたい

Cocos2d-xではRapidJSONというJSONパーサーを利用することができます。

github.com

今回初の利用となったのでドキュメントを読みながら覚えておきたいところをメモ書き程度にまとめます。 大体はチュートリアルに書かれていることと同じです。

チュートリアル
RapidJSON: Tutorial

Cocos2d-xで使う場合のinclude

必要に合わせて適宜

#include "json/rapidjson.h"
#include "json/document.h"
#include "json/stringbuffer.h"
#include "json/writer.h"

とりあえずダミーJSON

こちらを使って色々実験します。

const char json[] = " { \"test\" : \"テスト\", \"bool\" : true, \"n\": null, \"int\":123, \"pi\": 3.1416, \"array\":[1, 2, 3, 4] } ";

Parse

Document document;
if (document.Parse(json).HasParseError()) {
    log("parse error!!");
}

ValueとDocument

  • 全てのJSONの値はValue型として保持される
  • DocumentはDOMを表現しており、DOMツリーのroot Valueを最初から含んでいる
// パースエラーした状態でハンドリングせずにIsObject判定するとfalseになる
if (!document.IsObject()) {
    log("invalid!");
}

任意のメンバーが存在するか確認

document.HasMember("hello");

型チェック

// std::string
document.IsString("hello");
// bool
document.IsBool("bool");
// NULL
document.IsNull("null");
// 数値
document.IsNumber("pi");
// int
document.IsInt("int");
// double
document.IsDouble("pi");
// array
document.IsArray("array");

取得

// std::string
document.GetString("hello");
// bool
document.GetBool("bool");
// 数値
document.GetNumber("pi");
// int
document.GetInt("int");
// double
document.GetDouble("pi");
// array その1
const Value& a = document["a"];
for (SizeType i = 0; i < a.Size(); i++) // size_tの代わりにSizeType型を使う
  printf("a[%d] = %d\n", i, a[i].GetInt());
// array その2
// std::vectorとしてもアクセスできる
for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
    printf("%d ", itr->GetInt());

存在しているかわからないメンバーにアクセス

Value::ConstMemberIterator itr = document.FindMember("hello");
if (itr != document.MemberEnd())
    printf("%s %s\n", itr->value.GetString());

比較
==を利用した以下のような比較はできる

if (document["pi"] != 3.14) 

追加

第二引数はどんな型でも許容している

document.AddMember("addition", "ほげほげ", document.GetAllocator());

修正

document["hello"] = "日本語";
// こっちのほうが速い
document["hello"].SetString("rapidjson", 9);

Stringify

StringBuffer sb;
Writer<StringBuffer> writer(sb);
// インデントと改行を入れたい時
// PrettyWriter<StringBuffer> writer(sb);
document.Accept(writer);
sb.GetString();

まとめ

「Rapid」って謳っている位だから、かつてのJSONパーサーが遅かったかもしくはRapidJSONの速度が択一して早いのでしょうが如何せん初めて使ったのがこれだったのでその恩恵を理解できていませんが。。C++でこのくらい直感的にJSONが扱えると楽でいいですね。

オラッオラッ(=ω=.)

関連書籍

cocos2d-xではじめるスマートフォンゲーム開発 [cocos2d-x Ver.3対応] for iOS/Android

cocos2d-xではじめるスマートフォンゲーム開発 [cocos2d-x Ver.3対応] for iOS/Android