使用boost json_parser需要指导

时间:2015-01-23 20:17:14

标签: c++ json boost

我有一个类似的JSON文件:

[{"id":"1","this":"that"},{"id":"2","that":"this"}]

我对如何从增强文档调整XML 5分钟示例感到有点迷失。

到目前为止,我已经创建了一个结构和一些基础知识:

struct sheet {
 int id;
 std::string info;
}
using boost::property_tree::ptree;
ptree pt;
read_json(filename, pt);

但我不知道如何让BOOST_FOREACH等为我工作?

1 个答案:

答案 0 :(得分:2)

这是使用c ++ 11的快速演示

<强> Live On Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <sstream>
#include <iostream>

static std::string const sample = R"([{"id":"1","this":"that"},{"id":"2","that":"this"}])";

int main() {
    using namespace boost::property_tree;

    ptree pt;
    struct sheet { int id; std::string info; };

    std::istringstream iss(sample);
    read_json(iss, pt);

    std::vector<sheet> sheets;
    for(auto& e : pt)
    {
        std::string info = "(`this` not found)";

        auto this_property = e.second.get_child_optional("this");
        if (this_property)
            info = this_property->get_value(info);

        sheets.push_back(sheet {
            e.second.get_child("id").get_value(-1),
            info
        });
    }

    for(auto s : sheets)
        std::cout << s.id << "\t" << s.info << "\n";
}

打印:

1   that
2   (`this` not found)

更新 c ++ 03版本:

<强> Live On Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <sstream>
#include <iostream>
#include <boost/foreach.hpp>

struct sheet { int id; std::string info; };
static std::string const sample = "[{\"id\":\"1\",\"this\":\"that\"},{\"id\":\"2\",\"that\":\"this\"}]";

int main() {
    using namespace boost::property_tree;

    ptree pt;
    std::istringstream iss(sample);
    read_json(iss, pt);

    std::vector<sheet> sheets;
    BOOST_FOREACH(ptree::value_type e, pt)
    {
        std::string info = "(`this` not found)";

        boost::optional<ptree&> this_property = e.second.get_child_optional("this");
        if (this_property)
            info = this_property->get_value(info);

        sheet s;

        s.id   = e.second.get_child("id").get_value(-1);
        s.info = info;

        sheets.push_back(s);
    }

    BOOST_FOREACH(sheet s, sheets)
        std::cout << s.id << "\t" << s.info << "\n";
}

打印相同的