use*_*280 66 c++ json boost boost-propertytree
我是新手std::Map.什么是boost使用类型序列化和反序列化数据的最简单方法PropertyTree.我发现了一些使用的例子,std::Map但对我来说它们很模糊.
Art*_*mGr 91
注意,property_tree解释键作为路径,例如把一对"AB"= "Z"将创建一个{ "一":{ "B": "Z"}} JSON,不是{ "AB": "Z"} .否则,使用property_tree是微不足道的.这是一个小例子.
#include <sstream>
#include <map>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
void example() {
// Write json.
ptree pt;
pt.put ("foo", "bar");
std::ostringstream buf;
write_json (buf, pt, false);
std::string json = buf.str(); // {"foo":"bar"}
// Read json.
ptree pt2;
std::istringstream is (json);
read_json (is, pt2);
std::string foo = pt2.get<std::string> ("foo");
}
std::string map2json (const std::map<std::string, std::string>& map) {
ptree pt;
for (auto& entry: map)
pt.put (entry.first, entry.second);
std::ostringstream buf;
write_json (buf, pt, false);
return buf.str();
}
Run Code Online (Sandbox Code Playgroud)
Boost 1.75 及更高版本现在拥有强大的本机 JSON 库:
https://www.boost.org/doc/libs/develop/libs/json/doc/html/index.html
我不建议再使用 Boost.PropertyTree 的 JSON 算法,因为它们不完全符合规范。
| 归档时间: |
|
| 查看次数: |
56265 次 |
| 最近记录: |