您的位置:首页 > Web前端 > JavaScript

boost库解析json例子(二)

2015-07-17 16:06 525 查看
#include <boost/property_tree/ptree.hpp>

#include <boost/property_tree/json_parser.hpp>

#include<iostream>

#include <boost/foreach.hpp>

#include<string>

using namespace  std;

#include<sstream>

int main()  

{  
std::string str = "{\"code\":0,\"images\":[{\"url\":\"fmn057/20111221/1130/head_kJoO_05d9000251de125c.jpg\"},{\"url\":\"fmn057/20111221/1130/original_kJoO_05d9000251de125c.jpg\"}]}";  
using namespace boost::property_tree;  

std::stringstream ss(str);  
ptree pt;  
try{      
read_json(ss, pt);  
}  
catch(ptree_error & e) {  
return 1;   
}  

// 修改/增加一个key-value,key不存在则增加  
pt.put("upid", "00001");  

// 插入一个数组  

  ptree exif_array;  
ptree array1, array2, array3;  
array1.put("Make", "NIKON");  
array2.put("DateTime", "2011:05:31 06:47:09");  
array3.put("Software", "Ver.1.01");  
exif_array.push_back(std::make_pair("", array1));  
exif_array.push_back(std::make_pair("", array2));  
exif_array.push_back(std::make_pair("", array3));  

// exif_array.push_back(std::make_pair("Make", "NIKON"));  

// exif_array.push_back(std::make_pair("DateTime", "2011:05:31 06:47:09"));  

// exif_array.push_back(std::make_pair("Software", "Ver.1.01"));  

pt.put_child("exifs", exif_array);  
std::stringstream s2;  
write_json(s2, pt);  
std::string outstr = s2.str();  
cout<<outstr<<endl;
return 0;  

}  

下一个例子

#include <boost/property_tree/ptree.hpp>

#include <boost/property_tree/json_parser.hpp>

#include<iostream>

#include <boost/foreach.hpp>

#include<string>

using namespace  std;

int main()  

{  
std::string str = "{\"code\":0,\"images\":[{\"url\":\"fmn057\20111221\1130/head_kJoO_05d9000251de125c.jpg\"},{\"url\":\"fmn057\20111221\1130\original_kJoO_05d9000251de125c.jpg\"}]}";  
using namespace boost::property_tree;  
std::stringstream ss(str);  
ptree pt;  
try{      
read_json(ss, pt);  
}  
catch(ptree_error & e) {  
return 1;   
}  

try{  
int code = pt.get<int>("code");   // 得到"code"的value  
ptree image_array = pt.get_child("images");  // get_child得到数组对象  

cout<<code<<endl;

// 遍历数组  
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, image_array)  
{  
std::stringstream s;  
write_json(s, v.second);  
std::string image_item = s.str();  
cout<<image_item<<endl;
}  
}  
catch (ptree_error & e)  
{  
return 2;  
}  

return 0;  

}  


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: