boost解析json(2)

"{
    "A":1,
    "B":{
        "C":2,
        "D":3
    },
    "E":[
    {"F":4},
    {"F":5}
    ]
}"
#include<iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace std;
using namespace boost::property_tree;
//其实有点像std::list<string,ptree>,自己可以构造一个任何类型的节点插进去,特别数组类型,用法太灵活了
int main()
{
    std::string json = "{"A":1,"B":{"C":2,"D":3},"E":[{"F":4},{"F":5}]}";
    boost::property_tree::ptree pt,child1,child2 ;
    std::stringstream ss(json) ;
    boost::property_tree::read_json(ss, pt);
    child1 = pt.get_child("B");
    //针对树遍历
    for(auto c:child1)
    {
        cout<< c.first<<c.second.data()<<endl;
    }
    child2 = pt.get_child("E");
    for (ptree::iterator it = child2.begin(); it != child2.end(); ++it)
    {
        auto pt1 = it->second;//first为空
#if 0//输出first,second
        for (auto c: pt1)
        {
            cout<<c.first<<c.second.data();
        }
#endif
        //遍历数组F值,直接获取树里面的节点值
        auto i = pt1.get<int>("F");
        cout<<" F = "<< i <<endl;
    }
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/zzyoucan/p/3655810.html