序列化和反序列化助推JSON [英] Serializing and deserializing json with boost
本文介绍了序列化和反序列化助推JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新手, C ++
。什么是序列化和反序列化类型的std ::地图
使用升压
的数据最简单的方法。我发现一些例子使用 PropertyTree
,但他们还不清楚我。
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.
推荐答案
注意 property_tree
间$ P $点的按键为路径,例如把一对A·B=z的将创建一个{一:{B:Z}} JSON,而不是一个{A·B:Z}。否则,使用 property_tree
实在是微不足道。这里是一个小例子。
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.
#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();
}
这篇关于序列化和反序列化助推JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文