zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    CentOS 7 虚拟机的安装
    2 MySQL rpm
    01-在实体类上加了lombok的@Data注解
    02-myBatisPlus的wrapper接口的使用
    2 MySQL rpm 安装 --下载
    1-MySQL介绍
    MySQL的不归路
    电脑型号4 1500 内存大 机械大硬盘
    电脑型号3 1200 大硬盘
    电脑概览 2 1200 固态SSD
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3861240.html
Copyright © 2011-2022 走看看