使用boost来序列化和反序列化json

我是新手到c++ 。 使用boost序列化和反序列化std::Map数据的最简单方法是什么? 我发现了一些使用PropertyTree例子,但是对于我来说却很模糊。

请注意, property_tree将键解释为path,例如,将“ab”=“z”对创build为{“a”:{“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(); }