fc2ブログ

[c++] boost/property_treeによるjsonの解析

2009-12-25 | 11:31

boost/property_treeによるjsonの解析。

読み込むJSON
{

     "firstName": "John",

     "lastName": "Smith",

     "age": 20,

     "address": {

         "streetAddress": "21 2nd Street",

         "city": "New York",

         "state": "NY",

         "postalCode": 10021

     },

     "phoneNumbers": [

         { "type": "home", "number": "212 555-1234" },

         { "type": "fax", "number": "646 555-4567" }

     ],

     "newSubscription": false,

     "companyName": null
 }
C++ ソース
#include <string>
#include <set>
#include <exception>
#include <limits>
#include <iostream>

#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
#include "boost/foreach.hpp"

....

    using boost::property_tree::ptree;
    ptree pt;

    // ファイルから読み込む
    read_json("./sample.json", pt);

    // 文字列型として取得
    std::cout <<  pt.get<std::string>("firstName") << std::endl;

    // 数値型として取得
    std::cout <<  pt.get<int>("age") << std::endl;

    // 入れ子の取得
    std::cout <<  pt.get<std::string>("address.city") << std::endl;

    // 配列の走査
    BOOST_FOREACH(ptree::value_type &v, pt.get_child("phoneNumbers")){
        std::cout << v.second.get<std::string>("type") << std::endl;
        std::cout << v.second.get<std::string>("number") << std::endl;
    }

スポンサーサイト



Comment

Post a comment

Secret