boost库解析json例子(二)

#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;  

}  


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值