[轉] Boost解析JSON格式


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

 

解析Json的方法有很多,也有不少的第三方開源工具。這里僅介紹其中的一種,用Bosst解析。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");            
         }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM