Boost解析JSON格式

本文转自 http://blog.csdn.net/yqmfly/article/details/6914590

解析Json的方法有很多,也有不少的第三方开源工具。这里仅介绍其中的一种,用Boost解析。Boost库是一个可移植、提供源代码的C++库,作为标准库的后备,是C++标准化进程的发动机之一。 Boost库由C++标准委员会库工作组成员发起,其中有些内容有望成为下一代C++标准库内容。在C++社区中影响甚大,是不折不扣的“准”标准库。Boost由于其对跨平台的强调,对标准C++的强调,与编写平台无关。大部分boost库功能的使用只需包括相应头文件即可,少数(如正则表达式库,文件系统库等)需要链接库。但Boost中也有很多是实验性质的东西,在实际的开发中实用需要谨慎。

鉴于Boost的强大功能,就用Boost来解析Json格式,包括简单的及复杂的。

首先给出一个Json例子。

{ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },   

{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},   

{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }   ]} 

要解析Json,需要包括头文件。

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

还有

#include <string>
#include <vector>

#include <sstream.h>

using namespace boost::property_tree;
using namespace boost::gregorian;
using namespace boost;

接着,将上面这串Json赋给一个变量

string strJson ={ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },  

{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},   

{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }   ]} 

注:在C++中需要在“前面加入\进行转意。

接下来,给程序增加如下变量:

string stra,strc;
vector<string> vecStr;
ptree pt,p1,p2;
stringstream stream;

下面的程序是解析Json

    stream << strJson;
    read_json<ptree>( stream, pt);
    p1 = pt.get_child("people");
    for (ptree::iterator it = p1.begin(); it != p1.end(); ++it)
    {
        p2 = it->second; //first为空
        stra = p2.get<string>("firstName");
        vecStr.push_back(stra);   
    }

这样,vecStr中就有三个值,Brett,Jason,Elliotte,Json解析完成。

对于下面这样的Json格式,

{ "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },   { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },   { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }  ],  "authors": [   { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },   { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },   { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }   ],   "musicians": [   { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },   { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }   ] } 

就需要对上面的这两句程序稍微改动下就行了。

 p1 = pt.get_child("programmers");

stra = p2.get<string>("firstName");

对比一下,发现什么不同了吗?就是将参数稍微修改了一下。如果要得到musicians里面的firstName呢?就只要将p1 = pt.get_child("programmers");中的参数改成musicians;

如果Json里面嵌套了Json,则需要增加一个Ptree 变量pt3,pt4.使

p3 = p2.get_child("嵌套的值");

for (ptree::iterator ita = p3.begin(); ita != p3.end(); ++ita)
         {
             p4 = ita->second;
             strc = p4.get<string>("markerItemLink");            
         }

猜你喜欢

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