2014/07/30

おなじみC/C++から使えるJSONライブラリを紹介するコーナー。まずは過去のまとめ。

今回は json11 というライブラリ。

dropbox/json11 - GitHub
https://github.com/dropbox/json11

あの Dropbox が書いてる。C++ から使える JSON ライブラリは幾つかありますが、initializer_list が使える物がなかなか少ない。

json11 は以下の様に書ける。

Json my_json = Json::object {
    { "key1""value1" },
    { "key2"false },
    { "key3", Json::array { 123 } },
};

前回の jansson の記事で使ったサンプルを json11 で書くと以下の様になります。

※ネットワーク通信部分は前回のコードよりも省略しています

C++11 向けライブラリですのでコンパイル時のコマンドラインオプションに -std=c++11 を付ける必要があります。

#include <iostream>
#include "json11.hpp"
#include <curl/curl.h>

size_t
stream_write(char* ptr, size_t size, size_t nmemb, void* stream) {
  ((std::string*) stream)->append(std::string(ptr, size * nmemb));
  return size * nmemb;
}

int
main() {
  CURL* curl;
  std::string buf;
  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_URL, "https://api.github.com/legacy/repos/search/unko");
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl");
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stream_write);
  curl_easy_perform(curl);
  curl_easy_cleanup(curl);

  std::string err;
  json11::Json v = json11::Json::parse(buf, err);
  for (auto &k : v["repositories"].array_items()) {
    std::cout << k["username"].string_value() << std::endl;
    std::cout << k["name"].string_value() << std::endl;
    std::cout << k["description"].string_value() << std::endl << std::endl;
  }
}

とてもきれい。ライセンスは MIT なので業務でも使えます。

Posted at 19:40 | WriteBacks () | Edit
Edit this entry...

wikieditish message: Ready to edit this entry.






















A quick preview will be rendered here when you click "Preview" button.