Boost学习之读写json

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


昨天写了《 Boost学习之读写ini文件》,发现boost不止可以读写ini文件,还可以很方便的读写json文件。之前在C++中读写json比较抽象,从boost的语法可以很轻松的看出来。与读写ini一样,json格式,在boost中也被抽象为 property_tree

Boost中Json数据类型

在构建json文件时,我们只需要构建多个tree节点,按照对应的树形结构组合在一起即可。从boost写json文件API源码可以看出,property_tree支持三种类型,分别是valuearrayobject

  • 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()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值