LoginSignup
5
5

More than 5 years have passed since last update.

picojsonを使ってoF環境設定ファイルを読み書き

Last updated at Posted at 2013-12-02

ofxXmlSettingが使いにくかったので、picojson使ってみました。

config.json
{
    "LV":3,
    "HP":1,
    "MP":1,
    "sleepy":false,
    "hungry":true,
    "status":"カレー食べたい"
}

こんな感じのjsonファイルを用意して、

testApp.cpp

//testapp.cpp

#include "ofUtils.h"
#include <fstream>
#include "picojson.h"

void setup() {
    // load from bin/data/config.json
    std::string path = ofToDataPath("config.json");
    std::ifstream file;
    file.open(path.c_str());

    if(file.fail()) {
        std::cout << "Failed to open file : " << path << std::endl;
        return;
    }

    // to std::string
    std::istreambuf_iterator<char> first(file);
    std::istreambuf_iterator<char> last;
    std::string json_str(first, last);

    // parse json
    picojson::value json;
    std::string err;
    picojson::parse(json, json_str.begin(), json_str.end(), &err);

    picojson::object &o = json.get<picojson::object>();

    int lv = (int) o["LV"].get<double>();
    bool hungry = o["hungry"].get<bool>();
    std::string status = o["status"].get<std::string>();
}


こんな感じ。落ち着いたらクラスにまとめたい。ofxPicojsonに。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5