LoginSignup
24
25

More than 5 years have passed since last update.

dropbox/json11でC++でJSONを扱う

Last updated at Posted at 2014-06-24

概要

dropbox/json11はC++11対応のJSONライブラリで,初期化リストなどを使っていい感じに書けます.例えば,

{
    "name": "Nana Mizuki",
    "age": 34,
    "songs": [
        "ETERNAL BLAZE",
        "innocent starter"
    ]
}

というJSONは,json11では

json11::Json json_dayo = json11::Json::object {
    {"name" , "Nana Mizuki"},
    {"age"  , 34},
    {"songs" , Json::array { "ETERNAL BLAZE", "innocent starter" } },
};

のように書けます.いい感じです.使い方はtest.cppを見ればわかるかと思います.

std::istreamからJsonオブジェクトに

JSONをパースしてjson11のオブジェクトにするには,json11:Json::parse関数を使いますが,引数がstd::stringconst char*となっています.文字列で与えるということです.

std::istream (cinとかifstreamとか)からオブジェクトを作るにはストリーム→文字列→Jsonオブジェクトという流れになります.例えば

std::string buf, tmp;
while(std::getline(is,tmp) buf += tmp;          //isはstd::istream
json11::Json json = json11::Json::parse(buf);

とか書いとけばいけます

g++でのコンパイル

使い方の例が書いてあるtest.cppが同梱されていますが,Makefileを見るとコンパイラがclang++になっているので,
ここではg++makeする場合の注意を書きます.

  • Makefileを次のように書き直す

    test: json11.cpp json11.hpp test.cpp
      g++ -O -std=c++11 json11.cpp test.cpp -o test -fno-rtti -fno-exceptions
    
  • test.cppに次を追記

    test.cpp
    #include "cstring.hpp"
    
    • cstringをincludeしないと,test.cpp|92 col 66| error: 'memcmp' was not declared in this scopeとか言われます.
  • test.cppvoid parse_from_stdin()という関数がうまく機能しないので,次のように書き換える.

    • before
    test.cpp
    string buf;
    while (!std::cin.eof()) buf += std::cin.get();
    
    • after
    test.cpp
    string buf;
    string tmp;
    while (std::getline(std::cin, tmp)) buf += tmp;
    
    • cin.getって位置文字ずつとるしなんかヤダなぁ・・・
24
25
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
24
25