文章目录
昨天写了《 Boost学习之读写ini文件》,发现boost不止可以读写ini文件,还可以很方便的读写json文件。之前在C++中读写json比较抽象,从boost的语法可以很轻松的看出来。与读写ini一样,json格式,在boost中也被抽象为 property_tree。
Boost中Json数据类型
在构建json文件时,我们只需要构建多个tree节点,按照对应的树形结构组合在一起即可。从boost写json文件API源码可以看出,property_tree支持三种类型,分别是value 、array, object。
- value:系统默认数据类型;
- array:数组类型,可以嵌套自定义类型,在方括号中存放。
- object:使用者自定义的数据类型,在花括号中存放。
Boost写Json核心源码
以下代码段,是boost写入json核心代码。
template<class Ptree>
void write_json_helper(std::basic_ostream<typename Ptree::key_type::value_type> &stream,
const Ptree &pt,
int indent, bool pretty)
{
typedef typename Ptree::key_type::value_type Ch;
typedef typename std::basic_string<Ch> Str;
// Value or object or array
if (indent > 0 && pt.empty())
{
// Write value
Str data = create_escapes(pt.template get_value<Str>());
stream << Ch('"') << data << Ch('"');
}
else if (indent > 0 && pt.count(Str()) == pt.size())
{
// Write array
stream << Ch('[');
if (pretty) stream << Ch('\n');
typename Ptree::const_iterator it = pt.begin();
for (; it != pt.end(); ++it)
{
if (pretty) stream << Str(4 * (indent + 1), Ch(' '));
write_json_helper(stream, it->second, indent + 1, pretty);
if (boost::next(it) != pt.end())
stream << Ch(',');
if (pretty) stream << Ch('\n');
}
if (pretty) stream << Str(4 * indent, Ch(' '));
stream << Ch(']');
}
else
{
// Write object
stream << Ch('{');
if (pretty) stream << Ch('\n');
typename Ptree::const_iterator it = pt.begin();
for (; it != pt.end()

本文详细介绍了使用Boost库进行JSON文件的读写操作。通过构建不同类型的JSON数据(包括value、array和object),展示了如何创建和解析JSON文件。并提供了简单及复杂JSON示例的源代码,帮助读者理解Boost中JSON数据类型的使用。
最低0.47元/天 解锁文章
1374

被折叠的 条评论
为什么被折叠?



