boost解析json
时间:2010-06-09 来源:cdy_0
最近要用C++来处理JSON字符串,有些开源的库如jsoncpp等没太仔细研究。因为我要用到boost库,所以看了下 boost 1.4版中新增加了 PropertyTree ,其中有 JSON Parser JSON 分析器,c++可以用此来解析JSON 串,研究了一下,用起来还是比较方便的
例:
using namespace std;
using namespace boost::property_tree;
// example1
string s = "{\"a\":\"aa\",\"b\":{\"k\":\"kk\"}}";
stringstream stream(s);
read_json<ptree>( stream, pt);
cout<<pt.get<string>("a")<<endl; //输出为"aa"
cout<<pt.get<string>("b.k")<<endl; //输出"kk"
// example2
string s = "{\"data\":[{\"id\":1,\"name\":\"chen\"},{\"id\":2,\"name\":\"zhang\"}]}";
stringstream stream(s);
read_json<ptree>( stream, pt);
ptree pptt,ttt;
pptt = pt.get_child("data");
for (ptree::iterator it = pptt.begin(); it != pptt.end(); ++it){
ttt = it->second; //first为空
cout<<"id="<<ttt.get<int>("id")<<endl;
cout<<"name="<<ttt.get<string>("name")<<endl;
}
(可以再对ttt进行遍历,取出所有的key及value it->first.data()为key, it->second.data()为value)
--- 如若理解有误,敬请指正
例:
using namespace std;
using namespace boost::property_tree;
// example1
string s = "{\"a\":\"aa\",\"b\":{\"k\":\"kk\"}}";
stringstream stream(s);
read_json<ptree>( stream, pt);
cout<<pt.get<string>("a")<<endl; //输出为"aa"
cout<<pt.get<string>("b.k")<<endl; //输出"kk"
// example2
string s = "{\"data\":[{\"id\":1,\"name\":\"chen\"},{\"id\":2,\"name\":\"zhang\"}]}";
stringstream stream(s);
read_json<ptree>( stream, pt);
ptree pptt,ttt;
pptt = pt.get_child("data");
for (ptree::iterator it = pptt.begin(); it != pptt.end(); ++it){
ttt = it->second; //first为空
cout<<"id="<<ttt.get<int>("id")<<endl;
cout<<"name="<<ttt.get<string>("name")<<endl;
}
(可以再对ttt进行遍历,取出所有的key及value it->first.data()为key, it->second.data()为value)
--- 如若理解有误,敬请指正
相关阅读 更多 +