新人报道献礼:关于boost property_tree的一些探讨

本人最近工作中要用到c++解析json的方法,故在网上查了不少文章进行学习。

先发点牢骚:找了很多文章,但感觉多数内容雷同,深度不够,缺乏自己的分析和稍微深入一些的见解。

然后要感谢下面这2篇文章的作者:

http://www.voidcn.com/article/p-smrzeuyb-bud.html

http://einverne.github.io/post/2016/01/boost-learning-note-7.html

花了大约2-3个小时的时间仔细学习了一下,改写出了下面的一段测试代码:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>

using namespace boost::property_tree;
using namespace std;

void test1_2(){
    //http://www.voidcn.com/article/p-smrzeuyb-bud.html
    std::string const sample = R"(
    {
       "background": {
          "scripts": [ "name1.js", "name2.js", "name3.js" ]
       },
       "default_popup": "popup.html",
       "default_title": "__MSG_name__",
       "content_scripts": [ {
          "all_frames": true,
          "js": [ "name4.js", "name5.js", "name6.js" ],
          "match_about_blank": true,
          "matches": [ "http://*/*", "https://*/*" ],
          "run_at": "document_start"
       }, {
          "all_frames": true,
          "js": [ "include.postload.js" ],
          "match_about_blank": true,
          "matches": [ "http://*/*", "https://*/*" ],
          "run_at": "document_end"
       } ]
    })";    
    //printf("sample=%s\n",sample.c_str());
    
    ptree pt;
    stringstream stream1(sample);
    read_json(stream1,pt);
    
    struct temp_fxn1 {
        //ref: basic_ptree public member functions
        static int ptree_type(const ptree &pt){
            if(pt.size()>0){
                if(pt.begin()->first==""){
                    return 1;//array
                }else{
                    return 2;//object
                }
            }else{
                return 0;//leaf   
            }
        }
    };
    
    //遍历
    //for(auto &e : pt){
    //故意这样写:ref http://einverne.github.io/post/2016/01/boost-learning-note-7.html
    for(boost::property_tree::ptree::iterator it = pt.begin(); it != pt.end(); ++it){
        auto &e=*it;
        printf("===>\n");
        std::cout << e.first << ',' << e.second.get_value<std::string>()<<","<<temp_fxn1::ptree_type(e.second)<<"\n";
        printf("~~~~>\n");
        for(auto &c : e.second){
            std::cout << c.first << "\n";
        }
    }
}

这段代码实现了解析任意json字符串的功能(不包括出错处理),其中temp_fxn1::ptree_type()函数用于判断一个ptree节点类型。

注1:在解析json str是,只要str本身符合json的预压就可以生成一颗ptree,并不需要知道json str里面具体有哪些字段。这是多数文章未解决的问题。

注2:本人不喜欢 for(auto &e : pt){...}以及 BOOST_FOREACH 这样的写法。

致c++初学者:建议仔细走读一下这段程序,本人虽然水平不高,但还是花了不少心思的。这段代码里面包含了不少c++的知识点。

本人从事c++编码20余年,居然不知道R"..."这样的写法,实在惭愧。看来大家在一起交流是很重要的。

猜你喜欢

转载自www.cnblogs.com/oldfan1974/p/11391506.html
今日推荐