Serializing and deserializing JSON with Boost(使用 Boost 序列化和反序列化 JSON)
问题描述
我是 C++ 的新手.使用 boost 序列化和反序列化 std::Map 类型的数据的最简单方法是什么?我找到了一些使用 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 将键解释为路径,例如放置一对 "a.b"="z" 将创建一个 {"a":{"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();
}
这篇关于使用 Boost 序列化和反序列化 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Boost 序列化和反序列化 JSON
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
