如何使用boost :: property_tree用数组根解析JSON

时间:2014-11-14 18:58:13

标签: c++ json boost boost-propertytree

如何使用Boost.PropertyTree从阵列作为根节点获取JSON数据?

[
  {
      "ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
      "Type": "VM"
  }
]

1 个答案:

答案 0 :(得分:2)

数组元素只是一个名为""的键。属性树:

for (auto& array_element : pt) {
    for (auto& property : array_element.second) {
        std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
    }
}

打印

ID = cc7c3e83-9b94-4fb2-aaa3-9da458c976f7
Type = VM

<强> Live On Coliru

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

using namespace boost::property_tree;

int main()
{
    std::istringstream iss(R"([
    {
        "ID": "cc7c3e83-9b94-4fb2-aaa3-9da458c976f7",
        "Type": "VM"
    }
    ]
    )");

    ptree pt;
    json_parser::read_json(iss, pt);

    for (auto& array_element : pt) {
        for (auto& property : array_element.second) {
            std::cout << property.first << " = " << property.second.get_value<std::string>() << "\n";
        }
    }
}