我是新手,C ++。 什么是序列化和反序列化类型的数据最简单的方法std::Map
使用boost
。 我发现用一些例子PropertyTree
但他们是模糊的我。
Answer 1:
需要注意的是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();
}
文章来源: Serializing and deserializing JSON with Boost