C++ 使用 Boost 序列化和反序列化 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12394472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Serializing and deserializing JSON with Boost
提问by user1049280
I'm newbie to C++. What's the easiest way to serialize and deserialize data of type std::Map
using boost
. I've found some examples with using PropertyTree
but they are obscure for me.
我是 C++ 的新手。什么是序列化的最简单的方式和类型的反序列化数据std::Map
使用boost
。我发现了一些使用的例子,PropertyTree
但它们对我来说很模糊。
回答by ArtemGr
Note that property_tree
interprets the keys as paths, e.g. putting the pair "a.b"="z" will create an {"a":{"b":"z"}} JSON, not an {"a.b":"z"}. Otherwise, using property_tree
is trivial. Here is a little example.
请注意,property_tree
将键解释为路径,例如将 "ab"="z" 对将创建一个 {"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();
}