C++读取调用接口返回的json数据
1、引入头文件
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
2、读取json数据方法,http请求中的chunked传输数据会返回数据的长度,在最后一个chunked中其头部长度定为0
//读取json文件{"name":"zhangsan","age":25} template<class T> void readJson(const string& data, T& t) { if (strcmp(data.c_str(), "") != 0) { std::size_t start = data.find_first_of("{"); std::size_t end = data.find_last_of("}"); string res = data.substr(start, end - start + 1); std::stringstream ss(res); boost::property_tree::ptree pt; boost::property_tree::json_parser::read_json(ss, pt); t = pt.get<T>("name"); std::cout << "result:" << t << std::endl; } }
void postCustom(const string& url, const string& token) { boost::asio::io_service io; HttpBoost c(io); c.post(url, token); io.run(); string p=0; readJson(c.getResponse(),p); std::cout << c.getResponse() << std::endl; }
posted on 2023-08-31 09:33 lovezj9012 阅读(154) 评论(0) 编辑 收藏 举报