boost生成json

boost property_tree解析json文件相关文档如下:json_parser basic_ptree

json_parser:
read_json(filename, ptree):用于将filename文件中的内容读入ptree结构中。
write_json(filename, ptree):用于将ptree结构中的内容写入filename中。
basic_ptree:
self_type& get_child(path_type):
get_value<>: 以某种格式获得某个元素的值.例子:https://blog.csdn.net/shyanyang/article/details/44203169

自己的实践:
#include <iostream> #include <string> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp>
using namespace std; using namespace boost::property_tree; int main() { ptree pt; ptree children; ptree child1, child2, child3; child1.put("", 1); child2.put("", 2); child3.put("", 3); //write_json("test2.json", child1); //put空字符串后,马上转json会报错。 children.push_back(std::make_pair("", child1)); children.push_back(std::make_pair("", child2)); children.push_back(std::make_pair("", child3)); write_json("test3.json", children); //此时就不会报错. 此时不会生成数组. pt.add_child("MyArray", children); //add_child操作之后才生成数组的.如果要生成[]嵌套[],需要在外层再进行一次ptOutArray.push_back(make_pair("", ptInnerArray)),最后再进行add_child操作. write_json("test1.json", pt); return 0; }
test1.json内容:
{
"MyArray": [
"1",
"2",
"3"
]
}
test3.json内容:

{
"": "1",
"": "2",
"": "3"
}

 

另外的说明演示.

int main()
{
    ptree out;
    ptree pt;
    ptree children;
    ptree child;

    for (int i = 0; i < 5; i++)
    {
        child.put("", i);
//      children.push_back(std::make_pair("", child));
        children.put_child("", child);//add_child,put_child的key不能为空;而make_pair可以加入空值.
    }

    write_json("test3.json", children); //此时就不会报错

//  pt.push_back(make_pair("stock_pool", children)); //当key不为空时,add_child和push_back(make_pair())的效果是一样的.(除了我知道的键里含"."的情况,见下面的例子)
    pt.put_child("stock_pool", children);
    pt.add_child("stock_pool", children);

//     out.push_back(std::make_pair("data", pt));
    out.put_child("data", pt);
//     out.put_child("data", pt);//put操作时,key一样时只能不能够再添加上去,而add_child没有这个限制.
    ostringstream os;
    write_json(os, out);
    cout << os.str() << endl;
    write_json("test1.json", pt);
    return 0;
}

 property_tree中的put( , ),push_back(make_pair( , ))中的第一个参数可以为空字符串;而put_child( , ),add_child( , )的第一个参数不能为空字符串.

在进行add_child操作时,如果键中有"."的话,会割裂开来.比如键为"he.llo"时,此时,需要用push_back来替代add_child了.

{
    "he": {
        "llo": [
            [
                "1",
                "2",
                "3"
            ]
        ]
    }
}

 

posted @ 2018-12-21 17:29  心媛意码  阅读(937)  评论(0编辑  收藏  举报