boost之ptree学习(json)

#include <QtCore/QCoreApplication>

#include <boost/property_tree/ptree.hpp>

#include <boost/typeof/typeof.hpp>

#include <boost/property_tree/json_parser.hpp> 

#include <boost/property_tree/xml_parser.hpp>

#include <iostream> 

using namespace std;

using namespace boost::property_tree;

int main(int argc, char *argv[])

    QCoreApplication a(argc, argv); 

    string s = "{/"age/" : 26,/"study/":{/"language/":{/"one/":/"chinese/",/"two/":/"math/"},/"fee/":500,/"subject/":[{/"one/":/"china/"},{/"one/":/"Eglish/"}]},/"person/":[{/"id/":1,/"name/":/"chen/"},{/"id/":2,/"name/":/"zhang/"}],/"name/" : /"huchao/"}"; 

    ptree pt;

    stringstream stream(s); //这步不知道为什么要这样

    read_json<ptree>( stream, pt); 

    pt.put("study.language.one","physics");//修改数据(这步废了好久时间,最后通过读英文资料解决)

    pt.put("study.fee",600); 

    string s1=pt.get<string>("age");

    cout<<s1<<endl;

    string s2=pt.get<string>("name");

    cout<<s2<<endl;

    string s3=pt.get_child("study").get_child("language").get<string>("one");

    cout<<s3<<endl;

    string s4=pt.get_child("study").get<string>("fee");

    cout<<s4<<endl; 

    ptree p1,p2;

    p1 = pt.get_child("study").get_child("subject");//访问多级节点中的数组数据

    for (ptree::iterator it = p1.begin(); it != p1.end(); ++it)

    { 

        p2 = it->second; //first为空

        cout<<"subject="<<p2.get<string>("one")<<endl;

    } 

    return 0;

    return a.exec();

    //    pt.put("conf.theme", "Matrix Reloaded");

    //    pt.put("conf.clock_style", 13);

    //    pt.put("conf.gui", 0);

    //    pt.put("conf.urls.url","http://www.url4.org");

    //    pt.add("conf.urls.url","http://www.url4.org");

    //    write_json("conf.json", pt);

    //    read_json("conf.json",pt);

    //    cout<< pt.get<string>("conf.theme") <<endl;

    //    cout<< pt.get<int>("conf.clock_style") <<endl;

    //    cout<< pt.get<long>("conf.gui") <<endl;

    //    cout<< pt.get("conf.no_prop", 100) <<endl;

    //    BOOST_AUTO(child, pt.get_child("conf.urls"));

    //    for(BOOST_AUTO(pos,child.begin()); pos != child.end(); ++pos)

    //    {

    //        cout<<pos->second.data()<<",";

    //    }

    //    cout<<endl;

//         ptree pt_1,pt_11,pt_12;

//          pt_11.put("id","3445");

//          pt_11.put<int>("age",29);

//          pt_11.put("name","chen");

//          pt_12.push_back(make_pair("",pt_11));

//          pt_12.push_back(make_pair("",pt_11));

//          //replace or create child node "data"

//          pt_1.put_child("data",pt_12);

//          ostringstream os;

//          write_json(os,pt_1);

//          cout<<os.str()<

猜你喜欢

转载自blog.csdn.net/dddxxxx/article/details/87918592