json解析

#include<iostream>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//解析下面的json
//pair<string, ptree>
int main()
{
    using namespace boost::property_tree;
    std::string strJson = "{ \"people\": [{ \"firstName\": \"Brett\",\"lastName\":\"McLaughlin\", \"email\": \"aaaa\" },"
        "{ \"firstName\": \"Jason\", \"lastName\":\"Hunter\",\"email\": \"bbbb\"},"
        "{\"firstName\": \"Elliotte\", \"lastName\":\"Harold\", \"email\": \"cccc\" }]}";
    ptree pt;
    std::stringstream ss(strJson);
    
    read_json<ptree>(ss, pt);//读取到pt中去

    ptree people;
    people = pt.get_child("people");//获取people子节点
    for (auto p : people)
    {
        std::cout << p.first << std::endl;//其实这个数组时没有first的,今天研究了半天,结果这个事没有first的,只有second
    }

    getchar();
    return 0;
}

#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;//这样可以打印出first
    }
    child2 = pt.get_child("E");
    for (ptree::iterator it = child2.begin(); it != child2.end(); ++it)
    {
        auto pt1 = it->second;//first为空
#if 1//输出first,second
        /*for (auto c: pt1)
        {
        cout<<c.first<<c.second.data();
        }*/
        cout << pt1.get<int>("F");
#endif
#if 0
        //遍历数组F值,直接获取树里面的节点值
        auto i = pt1.get<int>("F");
        cout<<" F = "<< i <<endl;
#endif
    }
    system("pause");
    return 0;
}

json解析,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。