C ++:如何使用boost :: property_tree创建数组?

时间:2010-09-20 12:14:14

标签: c++ json boost boost-propertytree

我没有看到使用boost :: property树创建数组的方法。以下代码......

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

#include <iostream>

int main()
{
  try {
    boost::property_tree::ptree props;
    props.push_back(std::make_pair("foo", "bar"));
    props.push_back(std::make_pair("foo", "baz"));
    boost::property_tree::write_json("prob.json", props);
  } catch (const std::exception & ex) {
    std::cout << ex.what() << std::endl;
  }
}

......只是给了我......

{
  "foo": "bar",
  "foo": "baz"
}

boost :: property_tree上的文档很稀疏。如何使用boost :: property_tree?

创建JSON数组

1 个答案:

答案 0 :(得分:20)

如果你有一个子树,其唯一的节点有空键,那么它将被序列化为一个数组:

boost::property_tree::ptree array;
array.push_back(std::make_pair("", "bar"));
array.push_back(std::make_pair("", "baz"));

boost::property_tree::ptree props;
props.push_back(std::make_pair("array", array));

boost::property_tree::write_json("prob.json", props);