首页 > 代码库 > json解析2

json解析2

#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\":[3,4]}";    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;//这样可以打印出first    }    child2 = pt.get_child("E");    for (ptree::iterator it = child2.begin(); it != child2.end(); ++it)    {        auto pt1 = it->second;//first为空        for (auto c: pt1)//貌似有括号,不管是[]还是{}就是ptree,遍历树,感觉这个也不常用        {            cout<<c.first<<c.second.data();        }        cout << pt1.get<int>("F");//根据节点F取值,而这个second还是一棵树{"F":1}        cout << pt1.get_value<int>();//这种取值的方式不行,但这种情况可以,也是数组[1,2,3,4,5],应该是second直接就是他的值了        //遍历数组F值,直接获取树里面的节点值    }    system("pause");    return 0;}//JCK自解:有一个括号,就要一颗ptree。#include<iostream>#include <string>#include <sstream>#include <boost/property_tree/ptree.hpp>#include <boost/property_tree/json_parser.hpp>int  main(){    boost::property_tree::ptree ptree_root;    ptree_root.put("root","me_root");//放入Key,value,就是普通的向一个Ptree里面放入一个键值对    boost::property_tree::ptree ptree_items;    {        boost::property_tree::ptree pt;  //一棵树        /*pt.put<int>("item_1",20);*/        pt.put<int>("item_2",40);        ptree_items.push_back(make_pair("",pt));//相当于vector,作为一棵子树    }    {        boost::property_tree::ptree pt;//又一棵树        pt.put("item_1","30");        pt.put("item_2","60");        ptree_items.push_back(make_pair("",pt));    }    ptree_root.put_child("items", ptree_items );//作为子节点    boost::property_tree::write_json("C:\\file_path.json",ptree_root);    getchar();}

今天看的好晕,以前都写过的,又晕了